using System.IO;
using System.Diagnostics;
using System.Text.Json;
using XFEToolBox.Client.Core.Search;
using XFEToolBox.Client.Core.Search.Service;
namespace XFEToolBox.Client.Utilities;
/// Owns the lazily started local indexes; the palette never walks the disk while typing.
public sealed class FileSearchRuntime : IAsyncDisposable
{
private static readonly Lazy SharedInstance = new(() => new FileSearchRuntime(
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"XFEToolBox", "CrossVersion", "FileSearch"), new IndexingServiceClient()));
private readonly string cacheDirectory;
private readonly IIndexingServiceClient? indexingService;
private IndexingServiceStatus? serviceStatus;
private int consecutiveServiceProbeFailures;
private string? localRootsKey;
private bool initialized;
private readonly SemaphoreSlim initializationGate = new(1, 1);
private readonly CancellationTokenSource lifetime = new();
private readonly object contentGate = new();
private CancellationTokenSource scopeCancellation = new();
private CancellationTokenSource? contentCancellation;
private FileIndexService? files;
private Task? fileInitializationTask;
private string? fileInitializationError;
private bool isRestoringIndex;
private FileContentSearchService? content;
private bool contentEnabled;
private bool contentRefreshRequested;
private bool contentRefreshRunning;
private bool contentSuspended;
private bool lifetimeStopped;
private Task? contentRefreshTask;
private DateTimeOffset? contentSourceUpdated;
private long firstContentRequest;
private long lastContentRequest;
private long lastContentRun;
private int contentWorkerGeneration;
private string? contentRefreshError;
private bool disposed;
// Isolated runtimes (tests/custom caches) never silently connect to a machine-wide service.
public FileSearchRuntime(string cacheDirectory, IIndexingServiceClient? indexingService = null)
{
this.cacheDirectory = cacheDirectory;
this.indexingService = indexingService;
}
public static FileSearchRuntime Shared => SharedInstance.Value;
public static void RequestStopShared() { if (SharedInstance.IsValueCreated) SharedInstance.Value.RequestStop(); }
public static async Task StopSharedAsync()
{
if (SharedInstance.IsValueCreated) await SharedInstance.Value.DisposeAsync();
}
public event EventHandler? Changed;
public FileIndexStatus? Status
{
get
{
var state = files?.Status;
var remote = ServiceStatus;
if (state is null && remote is null) return null;
state ??= new(false, 0, 0, null, null, null);
return state with { IsScanning = state.IsScanning || Volatile.Read(ref isRestoringIndex) || remote?.IsIndexing == true,
Error = Volatile.Read(ref fileInitializationError) ?? state.Error ?? remote?.Error };
}
}
public IndexingServiceStatus? ServiceStatus => Volatile.Read(ref serviceStatus);
public bool IsUsingIndexingService => ServiceStatus is not null;
public bool IsRestoringIndex => Volatile.Read(ref isRestoringIndex);
public FileContentIndexStatus? ContentStatus => content?.Status is { } state
? state with { Error = Volatile.Read(ref contentRefreshError) ?? state.Error } : null;
public string ScopeText { get; private set; } = "所有本地磁盘";
public string? ScopePath { get; private set; }
// ConfigureAwait(false) does not move an already-completed await off the caller's
// thread. Keep the entire disk/options/lifecycle boundary on the worker pool.
public Task InitializeAsync(CancellationToken cancellationToken = default) =>
Task.Run(() => InitializeCoreAsync(cancellationToken), cancellationToken);
private async Task InitializeCoreAsync(CancellationToken cancellationToken)
{
await initializationGate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
ObjectDisposedException.ThrowIf(disposed, this);
lifetime.Token.ThrowIfCancellationRequested();
if (initialized) return;
ScopePath = await Task.Run(ReadScope, cancellationToken).ConfigureAwait(false);
await ConfigureBackendsAsync(probeService: true).ConfigureAwait(false);
initialized = true;
}
finally { initializationGate.Release(); }
}
public Task SetScopeAsync(string? folder, CancellationToken cancellationToken = default) =>
Task.Run(() => SetScopeCoreAsync(folder, cancellationToken), cancellationToken);
private async Task SetScopeCoreAsync(string? folder, CancellationToken cancellationToken)
{
await initializationGate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
ObjectDisposedException.ThrowIf(disposed, this);
lifetime.Token.ThrowIfCancellationRequested();
if (folder is not null)
{
folder = Path.GetFullPath(folder);
if (!Directory.Exists(folder)) throw new DirectoryNotFoundException("搜索目录不存在。");
}
// A freshly chosen isolated folder must never start the default all-drive crawler.
await Task.Run(() => SaveScope(folder), cancellationToken).ConfigureAwait(false);
lock (contentGate) contentSuspended = true;
await StopContentRefreshAsync().ConfigureAwait(false);
scopeCancellation.Cancel();
scopeCancellation.Dispose();
scopeCancellation = new();
var old = files;
files = null;
if (old is not null)
{
old.Changed -= Files_Changed;
await old.DisposeAsync().ConfigureAwait(false);
}
ScopePath = folder;
localRootsKey = null;
await ConfigureBackendsAsync(probeService: true).ConfigureAwait(false);
initialized = true;
lock (contentGate)
{
contentSourceUpdated = null;
lastContentRun = 0;
}
}
finally
{
lock (contentGate) contentSuspended = false;
initializationGate.Release();
}
if (Volatile.Read(ref contentEnabled)) ScheduleContentRefresh();
NotifyChanged();
}
public Task RebuildAsync(CancellationToken cancellationToken = default) =>
Task.Run(() => RebuildCoreAsync(cancellationToken), cancellationToken);
private async Task RebuildCoreAsync(CancellationToken cancellationToken)
{
await InitializeAsync(cancellationToken).ConfigureAwait(false);
await RefreshIndexingServiceAsync().ConfigureAwait(false);
await initializationGate.WaitAsync(cancellationToken).ConfigureAwait(false);
FileIndexService source;
CancellationTokenSource operation;
try
{
ObjectDisposedException.ThrowIf(disposed, this);
// Native service startup/replay is independent of the desktop lifecycle.
// Ordinary clients cannot request a privileged rebuild over IPC.
if (files is null) return;
source = files;
operation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, lifetime.Token, scopeCancellation.Token);
}
finally { initializationGate.Release(); }
using (operation) await source.RebuildAsync(operation.Token).ConfigureAwait(false);
}
public Task SetContentEnabledAsync(bool enabled, CancellationToken cancellationToken = default) =>
Task.Run(() => SetContentEnabledCoreAsync(enabled, cancellationToken), cancellationToken);
private async Task SetContentEnabledCoreAsync(bool enabled, CancellationToken cancellationToken)
{
if (enabled) await InitializeAsync(cancellationToken).ConfigureAwait(false);
await initializationGate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
ObjectDisposedException.ThrowIf(disposed, this);
lifetime.Token.ThrowIfCancellationRequested();
lock (contentGate)
{
if (enabled && !contentEnabled) lastContentRun = 0;
contentEnabled = enabled;
}
if (enabled)
{
// Text contents are deliberately never read by the privileged service.
// Opt-in body indexing obtains its source list with this user's ordinary rights.
if (initialized) await ConfigureBackendsAsync(probeService: false).ConfigureAwait(false);
content ??= CreateContentIndex();
ScheduleContentRefresh();
}
else
{
await StopContentRefreshAsync().ConfigureAwait(false);
if (initialized) await ConfigureBackendsAsync(probeService: false).ConfigureAwait(false);
}
}
finally { initializationGate.Release(); }
NotifyChanged();
}
public Task SearchAsync(string query, bool includeContent, int limit,
CancellationToken cancellationToken = default) =>
Task.Run(() => SearchCoreAsync(query, includeContent, limit, cancellationToken), CancellationToken.None);
private async Task SearchCoreAsync(string query, bool includeContent, int limit,
CancellationToken cancellationToken)
{
if (limit is < 1 or int.MaxValue) throw new ArgumentOutOfRangeException(nameof(limit));
if (cancellationToken.IsCancellationRequested || lifetimeStopped) return CancelledPage();
var parsed = FileSearchQuery.Parse(query);
if (parsed.Error is not null) return new([], false, TimeSpan.Zero, parsed.Error);
if (parsed.IsEmpty) return new([], false, TimeSpan.Zero);
// Initialization is shared by all queries; replacing an old query must not
// abort it or manufacture an exception on every keypress.
await InitializeAsync().ConfigureAwait(false);
await initializationGate.WaitAsync().ConfigureAwait(false);
FileSearchIndex? index;
FileContentSearchService? bodyIndex;
CancellationTokenSource operation;
IndexingServiceStatus? remoteState;
string? scope;
try
{
if (cancellationToken.IsCancellationRequested || lifetimeStopped) return CancelledPage();
ObjectDisposedException.ThrowIf(disposed, this);
index = files?.Index;
bodyIndex = includeContent && Volatile.Read(ref contentEnabled) && parsed.HasTextTerms ? content : null;
operation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, lifetime.Token, scopeCancellation.Token);
remoteState = ServiceStatus;
scope = ScopePath;
}
finally { initializationGate.Release(); }
using (operation)
{
var token = operation.Token;
var watch = Stopwatch.StartNew();
// UNC/uncovered scopes belong to the ordinary-user crawler, not the NTFS RPC.
var remoteApplicable = remoteState is not null && remoteState.IndexedRoots.Count > 0 &&
(scope is null || IndexingServiceProtocol.IsLocalPath(scope) &&
remoteState.IndexedRoots.Any(root => IsWithin(scope, root)));
if (remoteApplicable && query.Length > IndexingServiceProtocol.MaximumQueryLength)
return new([], false, watch.Elapsed,
$"独立索引服务的查询最多 {IndexingServiceProtocol.MaximumQueryLength:N0} 个字符,请缩短关键词。");
var remoteTask = remoteApplicable && indexingService is not null
? indexingService.SearchAsync(query, scope, Math.Min(limit + 1, IndexingServiceProtocol.MaximumResults), token)
: Task.FromResult(null);
Func? localFilter = !remoteApplicable ? null :
entry => !remoteState!.IndexedRoots.Any(root => IsWithin(entry.FullPath, root));
var nameTask = index is null ? Task.FromResult(new([], 0, TimeSpan.Zero)) :
Task.Run(() => index.TrySearch(query, limit: limit + 1, cancellationToken: token, filter: localFilter));
var contentTask = bodyIndex is not null && index is not null
? ReadContentPagesAsync(bodyIndex, index, query, limit + 1, token)
: Task.FromResult(new FileSearchResults([], 0, TimeSpan.Zero));
try { await Task.WhenAll(nameTask, contentTask, remoteTask).ConfigureAwait(false); }
catch (OperationCanceledException) when (token.IsCancellationRequested) { return CancelledPage(); }
if (token.IsCancellationRequested) return CancelledPage();
var names = await nameTask.ConfigureAwait(false);
if (names is null) return CancelledPage();
var bodies = await contentTask.ConfigureAwait(false);
var remote = await remoteTask.ConfigureAwait(false);
if (remoteApplicable && remote is null)
{
// A slow/busy query is not proof of a stopped service. Confirm liveness
// before launching a duplicate whole-disk fallback scan.
await initializationGate.WaitAsync().ConfigureAwait(false);
try
{
if (token.IsCancellationRequested || lifetimeStopped) return CancelledPage();
await ConfigureBackendsAsync(probeService: true).ConfigureAwait(false);
}
finally { initializationGate.Release(); }
if (token.IsCancellationRequested) return CancelledPage();
NotifyChanged();
return new([], false, watch.Elapsed, ServiceStatus is not null
? "索引服务正在忙或查询超时,请缩小搜索范围或细化关键词后重试。"
: "索引服务连接已中断,正在恢复普通权限本地搜索,请稍后重试。");
}
var merged = names.Items.Concat(remote?.Items ?? []).Concat(bodies.Items)
.GroupBy(item => item.Entry.FullPath, StringComparer.OrdinalIgnoreCase)
.Select(group => group.OrderBy(item => item.ContentMatch).ThenBy(item => item.Score).First())
.OrderBy(item => item.ContentMatch).ThenBy(item => item.Score)
.ThenBy(item => item.Entry.FullPath, StringComparer.OrdinalIgnoreCase).ToArray();
var hasMore = merged.Length > limit || names.TotalMatches > limit || bodies.TotalMatches > limit || remote?.HasMore == true;
return new(merged.Take(limit).ToArray(), hasMore, watch.Elapsed, remote?.Error);
}
}
private static FileSearchPage CancelledPage() => new([], false, TimeSpan.Zero) { IsCancelled = true };
private static async Task ReadContentPagesAsync(FileContentSearchService bodyIndex,
FileSearchIndex names, string query, int count, CancellationToken token)
{
var watch = Stopwatch.StartNew();
var matches = new List(Math.Min(count, 1000));
var offset = 0;
var total = 0;
do
{
var page = await bodyIndex.SearchAsync(query, offset, Math.Min(1000, count - matches.Count), token,
entry => names.ContainsPath(entry.FullPath)).ConfigureAwait(false);
total = page.TotalMatches;
matches.AddRange(page.Items);
offset += page.Items.Count;
if (page.Items.Count == 0) break;
}
while (matches.Count < count && offset < total);
return new(matches, total, watch.Elapsed);
}
public Task RefreshIndexingServiceAsync() => Task.Run(async () =>
{
if (indexingService is null || lifetimeStopped) return;
await initializationGate.WaitAsync().ConfigureAwait(false);
try
{
if (disposed || !initialized) return;
await ConfigureBackendsAsync(probeService: true).ConfigureAwait(false);
}
finally { initializationGate.Release(); }
NotifyChanged();
});
// Caller holds initializationGate. RPC/disk operations always run on a worker.
private async Task ConfigureBackendsAsync(bool probeService)
{
if (probeService && indexingService is not null)
{
var observed = await indexingService.GetStatusAsync(lifetime.Token).ConfigureAwait(false);
if (observed is not null)
{
consecutiveServiceProbeFailures = 0;
Volatile.Write(ref serviceStatus, observed);
}
else if (ServiceStatus is not null && ++consecutiveServiceProbeFailures < 3)
{
// A cold index can miss a short status deadline while real searches still
// succeed. Keep the last verified coverage through two independent misses;
// never start a duplicate whole-scope crawler on one transient timeout.
}
else
{
consecutiveServiceProbeFailures = 0;
Volatile.Write(ref serviceStatus, null);
}
}
SetScopeDescription(ScopePath);
IReadOnlyList configuredRoots = ScopePath is null ? FileIndexOptions.GetDefaultRoots() : [ScopePath];
var remote = ServiceStatus;
var localRoots = configuredRoots.Where(root => contentEnabled || remote is null ||
!remote.IndexedRoots.Any(covered => IsWithin(root, covered))).ToArray();
var key = string.Join('\n', localRoots.Select(Path.GetFullPath).Order(StringComparer.OrdinalIgnoreCase));
if (key == localRootsKey) return;
var previous = files;
files = null;
if (previous is not null)
{
previous.Changed -= Files_Changed;
await previous.DisposeAsync().ConfigureAwait(false);
}
localRootsKey = key;
if (localRoots.Length == 0)
{
Volatile.Write(ref isRestoringIndex, false);
fileInitializationTask = null;
Volatile.Write(ref fileInitializationError, null);
return;
}
files = CreateFileIndex(ScopePath, localRoots);
BeginFileInitialization(files);
lock (contentGate) contentSourceUpdated = null;
}
private void SetScopeDescription(string? folder)
{
ScopeText = folder is null ? "所有本地磁盘" : Path.GetFileName(Path.TrimEndingDirectorySeparator(folder));
if (string.IsNullOrEmpty(ScopeText)) ScopeText = folder ?? "所有本地磁盘";
}
private FileIndexService CreateFileIndex(string? folder, IReadOnlyList roots)
{
var options = new FileIndexOptions { CacheDirectory = cacheDirectory, Roots = roots };
var result = new FileIndexService(options);
result.Changed += Files_Changed;
return result;
}
private static bool IsWithin(string path, string root)
{
var normalized = Path.TrimEndingDirectorySeparator(root);
return string.Equals(Path.TrimEndingDirectorySeparator(path), normalized, StringComparison.OrdinalIgnoreCase) ||
path.StartsWith(Path.EndsInDirectorySeparator(normalized) ? normalized : normalized + Path.DirectorySeparatorChar,
StringComparison.OrdinalIgnoreCase);
}
private void BeginFileInitialization(FileIndexService source)
{
Volatile.Write(ref fileInitializationError, null);
Volatile.Write(ref isRestoringIndex, true);
// Return the index handle immediately. Cache restoration publishes batches,
// and searches must be able to query those batches before hydration finishes.
fileInitializationTask = ObserveFileInitializationAsync(source);
}
private async Task ObserveFileInitializationAsync(FileIndexService source)
{
try { await source.StartAsync(lifetime.Token).ConfigureAwait(false); }
catch (OperationCanceledException) { }
catch (Exception exception)
{
if (ReferenceEquals(source, files)) Volatile.Write(ref fileInitializationError, exception.Message);
Trace.WriteLine($"File index initialization: {exception}");
}
finally
{
if (ReferenceEquals(source, files))
{
Volatile.Write(ref isRestoringIndex, false);
NotifyChanged();
}
}
}
private FileContentSearchService CreateContentIndex()
{
var result = new FileContentSearchService(Path.Combine(cacheDirectory, "Content"));
result.Changed += Content_Changed;
return result;
}
private void Files_Changed(object? sender, EventArgs e)
{
if (!ReferenceEquals(sender, files)) return;
var state = files?.Status;
lock (contentGate)
{
if (contentEnabled && !contentSuspended && state is { IsScanning: false } &&
state.LastUpdatedUtc != contentSourceUpdated)
ScheduleContentRefreshLocked();
}
NotifyChanged();
}
private void ScheduleContentRefresh()
{
lock (contentGate) ScheduleContentRefreshLocked();
}
private void ScheduleContentRefreshLocked()
{
if (!contentEnabled || contentSuspended || lifetimeStopped || disposed) return;
var now = Stopwatch.GetTimestamp();
if (!contentRefreshRequested) firstContentRequest = now;
lastContentRequest = now;
contentRefreshRequested = true;
if (!contentRefreshRunning) StartContentWorkerLocked();
}
private void StartContentWorkerLocked()
{
contentCancellation?.Dispose();
contentCancellation = CancellationTokenSource.CreateLinkedTokenSource(lifetime.Token);
var token = contentCancellation.Token;
var generation = ++contentWorkerGeneration;
contentRefreshRunning = true;
contentRefreshTask = Task.Run(() => RefreshContentLoopAsync(generation, token), CancellationToken.None);
}
private async Task RefreshContentLoopAsync(int generation, CancellationToken token)
{
try
{
while (true)
{
FileIndexService? source;
FileContentSearchService? bodyIndex;
TimeSpan delay;
lock (contentGate)
{
token.ThrowIfCancellationRequested();
if (!contentRefreshRequested || !contentEnabled || contentSuspended) return;
source = files;
bodyIndex = content;
var now = Stopwatch.GetTimestamp();
// Debounce quiet writes for two seconds. Sustained writes cannot postpone forever:
// refresh by ten seconds, and never stat the whole file set more than once per ten seconds.
var debounceDue = Math.Min(lastContentRequest + 2L * Stopwatch.Frequency,
firstContentRequest + 10L * Stopwatch.Frequency);
var due = Math.Max(debounceDue, lastContentRun == 0 ? 0 : lastContentRun + 10L * Stopwatch.Frequency);
delay = due > now ? Stopwatch.GetElapsedTime(now, due) : TimeSpan.Zero;
}
if (delay > TimeSpan.Zero)
{
await Task.Delay(delay, token).ConfigureAwait(false);
continue;
}
if (source is null || bodyIndex is null) return;
if (source.Status.IsScanning || source.Status.LastUpdatedUtc is null)
{
await Task.Delay(500, token).ConfigureAwait(false);
continue;
}
DateTimeOffset? updated;
lock (contentGate)
{
token.ThrowIfCancellationRequested();
if (!contentEnabled || contentSuspended) return;
contentRefreshRequested = false;
lastContentRun = Stopwatch.GetTimestamp();
updated = source.Status.LastUpdatedUtc;
contentRefreshError = null;
}
var entries = source.Index.GetEntriesSnapshot();
await bodyIndex.EnsureIndexAsync(entries, token).ConfigureAwait(false);
lock (contentGate)
{
if (ReferenceEquals(source, files)) contentSourceUpdated = updated;
}
}
}
catch (OperationCanceledException) when (token.IsCancellationRequested) { }
catch (Exception exception)
{
Volatile.Write(ref contentRefreshError, exception.Message);
Trace.WriteLine($"File content indexing: {exception}");
NotifyChanged();
}
finally
{
lock (contentGate)
{
if (generation == contentWorkerGeneration)
{
contentRefreshRunning = false;
// A mutation may arrive while this task exits. Publish its idle state while locked,
// then start its replacement in the same lock instead of inspecting Task.IsCompleted.
if (contentRefreshRequested && contentEnabled && !contentSuspended && !lifetimeStopped &&
!disposed && !token.IsCancellationRequested)
StartContentWorkerLocked();
}
}
}
}
private async Task StopContentRefreshAsync()
{
Task? pending;
lock (contentGate)
{
contentRefreshRequested = false;
contentCancellation?.Cancel();
pending = contentRefreshTask;
}
if (content is not null) await content.StopAsync().ConfigureAwait(false);
if (pending is not null) await pending.ConfigureAwait(false);
}
private void Content_Changed(object? sender, EventArgs e) => NotifyChanged();
private void NotifyChanged()
{
foreach (var handler in Changed?.GetInvocationList().Cast() ?? [])
{
try { handler(this, EventArgs.Empty); }
catch (Exception error) { Trace.WriteLine($"File search status subscriber: {error}"); }
}
}
private string? ReadScope()
{
try
{
var path = Path.Combine(cacheDirectory, "settings.json");
if (!File.Exists(path) || new FileInfo(path).Length > 65536) return null;
var scope = JsonSerializer.Deserialize(File.ReadAllText(path));
return scope?.Folder is { Length: > 0 } folder && Directory.Exists(folder) ? folder : null;
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or JsonException or ArgumentException)
{ return null; }
}
private void SaveScope(string? folder)
{
Directory.CreateDirectory(cacheDirectory);
var path = Path.Combine(cacheDirectory, "settings.json");
var temporary = path + ".tmp";
File.WriteAllText(temporary, JsonSerializer.Serialize(new SearchScope(folder)));
File.Move(temporary, path, overwrite: true);
}
private void RequestStop()
{
lock (contentGate)
{
if (lifetimeStopped) return;
lifetimeStopped = true;
lifetime.Cancel();
contentCancellation?.Cancel();
}
files?.RequestStop();
}
public ValueTask DisposeAsync() => new(Task.Run(DisposeCoreAsync));
private async Task DisposeCoreAsync()
{
await initializationGate.WaitAsync().ConfigureAwait(false);
try
{
if (disposed) return;
disposed = true;
lock (contentGate)
{
contentEnabled = false;
contentSuspended = true;
}
RequestStop();
scopeCancellation.Cancel();
await StopContentRefreshAsync().ConfigureAwait(false);
var source = files;
files = null;
if (source is not null)
{
source.Changed -= Files_Changed;
await source.DisposeAsync().ConfigureAwait(false);
}
if (fileInitializationTask is not null) await fileInitializationTask.ConfigureAwait(false);
if (content is not null)
{
content.Changed -= Content_Changed;
await content.DisposeAsync().ConfigureAwait(false);
}
scopeCancellation.Dispose();
contentCancellation?.Dispose();
lifetime.Dispose();
}
finally { initializationGate.Release(); }
}
private sealed record SearchScope(string? Folder);
}
public sealed record FileSearchPage(IReadOnlyList Items, bool HasMore, TimeSpan Elapsed, string? Error = null)
{
public bool IsCancelled { get; init; }
}