diff --git a/docs/linux-port/performance-tracing.md b/docs/linux-port/performance-tracing.md new file mode 100644 index 000000000000..795707591d1b --- /dev/null +++ b/docs/linux-port/performance-tracing.md @@ -0,0 +1,74 @@ +# Slow-action tracing (issue #131) + +Set `FILES_TRACE=1` before starting Files. Other values leave tracing disabled. The flag is read once per process; +disabled scopes do not allocate, read clocks, or queue records. Enabled tracing buffers at most 1,024 records, +drops records when full, and writes `[files-trace]` lines to stderr on a worker. Slow stderr must not stall the UI. +Buffered records can be lost at shutdown; this is diagnostic output, not an audit log. + +For an authorised headless verification run, from the repository root: + +```bash +FILES_TRACE=1 FILES_SANDBOX_DRIVES=scripts/linux/showcase-drives.txt \ + nice -n 19 scripts/linux/headless-run.sh -s 40 -o /tmp/files-perf-actions -a /tmp/perf-actions.txt +``` + +Use only the private Xvfb harness and its throwaway HOME/session bus. Never use the real display, real home, +real desktop settings, or host inotify-limit changes. The harness captures stderr in `app.log` and cleans up +its processes. Default dry-run launches do not measure real process spawning; use a disposable fixture program +in the sandbox if actual spawn measurements are needed. + +Each record carries `id`, `parent`, `operation`, elapsed `ms` (monotonic clock), completion `thread`, optional +`ui` flag, and `outcome`. Parent IDs follow async execution context. A thread ID identifies the completion +thread, not a thread occupied throughout an await. No paths, arguments, selected names, bus addresses, +message bodies, credentials, or process output are included. + +| Operation | Measured boundary | +| --- | --- | +| `context-menu-build` | Item/background flyout opening through model building and awaited extension loading; excludes visible-frame latency and deferred submenu loading. | +| `open-with-load` | MIME lookup, application query and default lookup on a worker; excludes UI icon decoding/population. | +| `open-with-query` | Registry worker query, including candidate resolution. | +| `parsed-file-cache` | File identity check plus parsing on a miss; outcomes `hit`, `miss`, `missing-or-unreadable`. | +| `service-menu-scan` | Directory scan, cached parsing and selection filtering; MIME lookup precedes this scope. | +| `tag-db-save` | Actual atomic database save attempt; unchanged tags/empty missing entries produce no save record. | +| `dbus-connect` | Session/system connection attempt, including its timeout. | +| `dbus.*` | Outbound call to reply/fault, grouped by platform feature. Caller timeouts can occur before this record; a call that never completes has no completion record. | +| `process-spawn` | `Process.Start` only, across platform runners. | +| `process-wrapper-exit` | Detached-launch wrapper wait, not external application readiness. | +| `folder-enumeration` | Batch enumerator lifetime, including consumer time between batches. | +| `folder-enumeration-batch` | Directory entries/metadata read on a worker, excluding consumer/UI rendering time. | + +`completed-or-unwound` means the scope ended, including exception/cancellation paths; it does not claim success. +D-Bus records explicitly report `reply`/`fault`. Correlate caller logs to distinguish cancellations/timeouts. + +Application, association and MIME mapping caches check device/inode/mode/size/nanosecond mtime on every use. +Atomic replacements, edits, removals and user overrides are visible on the next query without watcher resources +or an invalidation delay. Directory scans still discover newly installed entries, including nested application +entries. Caches are instance/culture specific and bounded to 4,096 parsed files each. KDE menu parsing uses +no-follow identities; launch-time strict parsing and identity checks remain independent of this display cache. +Open With populates on pointer entry or keyboard focus, with a localized loading placeholder, and queries run +off the UI thread. Tag edits use one ordered background write queue; failed database saves stay dirty for retry. + +Watcher degradation is logged once per watcher, including the polling interval and exception type (or forced +polling), without a folder path. Existing post-operation refresh hooks also refresh polling-backed listings, +so app create/rename/paste/trash/restore actions need not wait for the normal two-second external-change poll. + +## Pending private Xvfb checks + +1. Repeat file and background right-clicks cold/warm, including mouse and keyboard Open With activation. + Confirm the loading placeholder resolves, cancellation on closing/navigation is safe, applications/default + labels remain correct, and registry work reports `ui=False`. Compare menu/query/scan timings (median/p95). +2. Seed sandbox application associations and KDE service menus; add, edit, atomically replace and remove them + between queries. Confirm overrides, Hidden/NoDisplay, removal lists, localization, selection filtering and + fresh execution-time validation still behave correctly. +3. Browse a large tagged/untagged fixture directory repeatedly. Confirm warm reads do not emit tag saves; + edit/remove tags rapidly and reopen Files to check the final database/xattr values and write ordering. +4. Inject a test watcher factory using `FolderWatcherOptions.ForcePolling` (do not alter host limits). Verify + one fallback log, prompt create/rename/copy/move/trash/restore updates after our operations, stable selection, + no duplicate rows when the next poll arrives, and ordinary polling of external fixture edits. Check native + watcher behaviour separately. The production app has no force-polling environment switch. +5. Use only private mock D-Bus services and a harmless disposable process fixture to confirm trace output for + delayed replies, faults, spawns and wrapper exit. Compare tracing off/on responsiveness; verify off produces + no trace records. Navigation should emit enumeration and batch timings; no record should expose fixture paths. + +These checks were not run by the implementation agent. Xvfb software rendering does not establish real KDE +compositor/GPU performance or production D-Bus daemon latency. diff --git a/src/Files.App/App.xaml.cs b/src/Files.App/App.xaml.cs index 905019b1b19e..c414d743f742 100644 --- a/src/Files.App/App.xaml.cs +++ b/src/Files.App/App.xaml.cs @@ -81,6 +81,7 @@ public App() AppDomain.CurrentDomain.ProcessExit += static (_, _) => SafetyExtensions.IgnoreExceptions(() => Ioc.Default.GetService()?.TryCompleteAndFlush(TimeSpan.FromSeconds(2))); #if !WINDOWS + AppDomain.CurrentDomain.ProcessExit += static (_, _) => FileTagsHelper.DrainPendingWritesAsync().GetAwaiter().GetResult(); AppDomain.CurrentDomain.ProcessExit += static (_, _) => SafetyExtensions.IgnoreExceptions(ArchiveOpenTempStore.CleanupCurrentProcess); _ = Task.Run(ArchiveOpenTempStore.CleanupStale); #endif diff --git a/src/Files.App/Data/Factories/ShellContextFlyoutFactory.Linux.cs b/src/Files.App/Data/Factories/ShellContextFlyoutFactory.Linux.cs index 24cc23145116..f675ec3658cc 100644 --- a/src/Files.App/Data/Factories/ShellContextFlyoutFactory.Linux.cs +++ b/src/Files.App/Data/Factories/ShellContextFlyoutFactory.Linux.cs @@ -42,9 +42,14 @@ private static async Task LoadOpenWithItemsAsync(ContextMenuFlyoutItemViewModel var registry = Ioc.Default.GetRequiredService(); var launcher = Ioc.Default.GetRequiredService(); - var mime = await mimeTypes.GetMimeTypeAsync(path, cancellationToken); - var apps = await registry.GetApplicationsForMimeTypeAsync(mime, cancellationToken); - var defaultApp = await registry.GetDefaultApplicationAsync(mime, cancellationToken); + var (apps, defaultApp) = await Task.Run(async () => + { + using var trace = Files.Platform.Abstractions.Diagnostics.PerformanceTrace.Begin("open-with-load", false); + var mime = await mimeTypes.GetMimeTypeAsync(path, cancellationToken).ConfigureAwait(false); + var applications = await registry.GetApplicationsForMimeTypeAsync(mime, cancellationToken).ConfigureAwait(false); + var preferred = await registry.GetDefaultApplicationAsync(mime, cancellationToken).ConfigureAwait(false); + return (applications, preferred); + }, cancellationToken); var items = model.Items ??= []; foreach (var app in apps) diff --git a/src/Files.App/Data/Items/ListedItem.cs b/src/Files.App/Data/Items/ListedItem.cs index 8ca68abc565a..12bb1e8f31c2 100644 --- a/src/Files.App/Data/Items/ListedItem.cs +++ b/src/Files.App/Data/Items/ListedItem.cs @@ -116,6 +116,10 @@ public string[]? FileTags get => fileTags; set { +#if !WINDOWS + if (fileTags is not null && fileTags.SequenceEqual(value, StringComparer.Ordinal)) + return; +#endif // fileTags is null when the item is first created var fileTagsInitialized = fileTags is not null; if (SetProperty(ref fileTags, value)) @@ -124,8 +128,10 @@ public string[]? FileTags if (fileTagsInitialized) { var path = this.GetRequiredPath(); +#if WINDOWS var dbInstance = FileTagsHelper.GetDbInstance(); dbInstance.SetTags(path, FileFRN, value); +#endif _ = FileTagsHelper.WriteFileTagAsync(path, value); } diff --git a/src/Files.App/Platforms/Desktop/Program.cs b/src/Files.App/Platforms/Desktop/Program.cs index 782c513c7a98..5e44320fc662 100644 --- a/src/Files.App/Platforms/Desktop/Program.cs +++ b/src/Files.App/Platforms/Desktop/Program.cs @@ -109,7 +109,14 @@ public static int Main(string[] args) })) .Build(); - host.Run(); + try + { + host.Run(); + } + finally + { + FileTagsHelper.DrainPendingWritesAsync().GetAwaiter().GetResult(); + } SingleInstance?.DisposeAsync().AsTask().GetAwaiter().GetResult(); diff --git a/src/Files.App/Platforms/Desktop/ViewModels/ShellViewModel.Linux.cs b/src/Files.App/Platforms/Desktop/ViewModels/ShellViewModel.Linux.cs index 688552bbca31..709d88255cfd 100644 --- a/src/Files.App/Platforms/Desktop/ViewModels/ShellViewModel.Linux.cs +++ b/src/Files.App/Platforms/Desktop/ViewModels/ShellViewModel.Linux.cs @@ -27,6 +27,7 @@ namespace Files.App.ViewModels public sealed partial class ShellViewModel { private Files.Platform.Abstractions.Watching.IFolderWatcher? _linuxWatcher; + public bool IsLinuxWatcherPolling => _linuxWatcher?.IsPolling == true; private CancellationTokenSource? _linuxRefreshDebounce; private readonly List _linuxRepositoryWatchers = []; private Action? _linuxTrashUnsubscribe; diff --git a/src/Files.App/Services/Settings/FileTagsSettingsService.cs b/src/Files.App/Services/Settings/FileTagsSettingsService.cs index d45fdd58adad..b4375da3d02c 100644 --- a/src/Files.App/Services/Settings/FileTagsSettingsService.cs +++ b/src/Files.App/Services/Settings/FileTagsSettingsService.cs @@ -187,6 +187,9 @@ private int GetTagIndex(string uid) private void UntagAllFiles(string uid) { +#if !WINDOWS + _ = FileTagsHelper.UntagAllFilesAsync(uid); +#else var tagDoDelete = new string[] { uid }; foreach (var item in FileTagsHelper.GetDbInstance().GetAll()) @@ -198,6 +201,7 @@ private void UntagAllFiles(string uid) item.Tags.Except(tagDoDelete).ToArray()); } } +#endif } private IJsonSettingsSerializer GetJsonSettingsSerializer() diff --git a/src/Files.App/Utils/FileTags/FileTagsDatabase.Linux.cs b/src/Files.App/Utils/FileTags/FileTagsDatabase.Linux.cs index a7e57a493dde..84d1680ce46e 100644 --- a/src/Files.App/Utils/FileTags/FileTagsDatabase.Linux.cs +++ b/src/Files.App/Utils/FileTags/FileTagsDatabase.Linux.cs @@ -3,6 +3,9 @@ #if !WINDOWS using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; using System.IO; using JsonSerializer = System.Text.Json.JsonSerializer; @@ -17,19 +20,28 @@ public sealed partial class FileTagsDatabase { private readonly object _gate = new(); private Dictionary? _entries; + private bool _dirty; + private readonly string? _databasePath; - private static string DatabasePath - => Path.Combine(Ioc.Default.GetRequiredService().DataDirectory, "filetags.json"); + public FileTagsDatabase() { } + + internal FileTagsDatabase(string databasePath) => _databasePath = databasePath; + + private string DatabasePath + => _databasePath ?? Path.Combine(Ioc.Default.GetRequiredService().DataDirectory, "filetags.json"); public void SetTags(string filePath, ulong? frn, string[] tags) { lock (_gate) { var entries = Load(); - if (tags is []) - entries.Remove(filePath); - else - entries[filePath] = new TaggedFile { FilePath = filePath, Tags = tags }; + var changed = tags.Length == 0 + ? entries.Remove(filePath) + : !entries.TryGetValue(filePath, out var current) || !current.Tags.SequenceEqual(tags, StringComparer.Ordinal); + if (!changed && !_dirty) + return; + if (tags.Length > 0 && changed) + entries[filePath] = new TaggedFile { FilePath = filePath, Tags = (string[])tags.Clone() }; Save(entries); } @@ -37,7 +49,7 @@ public void SetTags(string filePath, ulong? frn, string[] tags) public void UpdateTag(string oldFilePath, ulong? frn, string? newFilePath) { - if (newFilePath is null) + if (newFilePath is null || string.Equals(oldFilePath, newFilePath, StringComparison.Ordinal)) return; lock (_gate) @@ -63,7 +75,7 @@ public string[] GetTags(string? filePath, ulong? frn) return []; lock (_gate) - return Load().TryGetValue(filePath, out var tagged) ? tagged.Tags : []; + return Load().TryGetValue(filePath, out var tagged) ? (string[])tagged.Tags.Clone() : []; } public IEnumerable GetAll() @@ -92,6 +104,12 @@ public void Import(string json) entries[tag.FilePath] = tag; } + var current = Load(); + if (!_dirty && current.Count == entries.Count && entries.All(pair => + current.TryGetValue(pair.Key, out var existing) && existing.Frn == pair.Value.Frn && + existing.Tags.SequenceEqual(pair.Value.Tags, StringComparer.Ordinal))) + return; + Save(entries); } } @@ -131,7 +149,9 @@ private Dictionary Load() private void Save(Dictionary entries) { + using var trace = Files.Platform.Abstractions.Diagnostics.PerformanceTrace.Begin("tag-db-save"); _entries = entries; + _dirty = true; string? temp = null; try @@ -142,6 +162,7 @@ private void Save(Dictionary entries) File.WriteAllText(temp, JsonSerializer.Serialize(entries.Values.ToList(), AppJsonSerializerContext.Default.ListTaggedFile)); File.Move(temp, path, overwrite: true); temp = null; + _dirty = false; } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { diff --git a/src/Files.App/Utils/FileTags/FileTagsHelper.Linux.cs b/src/Files.App/Utils/FileTags/FileTagsHelper.Linux.cs index aa55355e7076..b15a2bafc423 100644 --- a/src/Files.App/Utils/FileTags/FileTagsHelper.Linux.cs +++ b/src/Files.App/Utils/FileTags/FileTagsHelper.Linux.cs @@ -4,7 +4,10 @@ #if !WINDOWS using Files.Platform.Abstractions.Tags; using Microsoft.Extensions.Logging; -using Windows.Storage; +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; namespace Files.App.Utils.FileTags { @@ -35,29 +38,96 @@ public static string[] ReadFileTag(string filePath) return GetDbInstance().GetTags(filePath, null); } - public static Task WriteFileTagAsync(string filePath, string[] tag, CancellationToken cancellationToken = default) + public static Task ReadAndUpdateFileTagsAsync(string filePath) { - try + return EnqueueWrite(() => { - cancellationToken.ThrowIfCancellationRequested(); + var tags = ReadFileTag(filePath); + GetDbInstance().SetTags(filePath, null, tags); + return tags; + }, Array.Empty()); + } - GetDbInstance().SetTags(filePath, null, tag); + private static readonly object writeGate = new(); + private static Task pendingWrite = Task.CompletedTask; - // Best effort: the database already holds the tags, so a file system without xattr support is not an error - var store = Ioc.Default.GetService(); - if (store is not null) + public static Task WriteFileTagAsync(string filePath, string[] tag, CancellationToken cancellationToken = default) + { + if (cancellationToken.IsCancellationRequested) return Task.FromResult(false); + var tags = (string[])tag.Clone(); + var store = Ioc.Default.GetService(); + var settings = Ioc.Default.GetRequiredService(); + var names = settings.GetTagsByIds(tags)?.Select(x => x.Name).ToArray() ?? []; + return EnqueueWrite(() => !cancellationToken.IsCancellationRequested && WriteTags(filePath, tags, names, store), false); + } + + public static Task UntagAllFilesAsync(string uid) + { + var store = Ioc.Default.GetService(); + var settings = Ioc.Default.GetRequiredService(); + var namesById = settings.FileTagList.ToDictionary(tag => tag.Uid, tag => tag.Name); + return EnqueueWrite(() => + { + var succeeded = true; + foreach (var item in GetDbInstance().GetAll()) { - var settings = Ioc.Default.GetRequiredService(); - var names = settings.GetTagsByIds(tag)?.Select(x => x.Name).ToArray() ?? []; - if (!store.WriteTags(filePath, names)) - App.Logger?.LogDebug("Extended attributes are not available for '{FilePath}'; tags are kept in the database only.", LogPathHelper.RedactPath(filePath)); + if (!item.Tags.Contains(uid)) continue; + var tags = item.Tags.Where(tag => tag != uid).ToArray(); + var names = tags.Where(namesById.ContainsKey).Select(tag => namesById[tag]).ToArray(); + succeeded &= WriteTags(item.FilePath, tags, names, store); } + return succeeded; + }, false); + } + + public static async Task DrainPendingWritesAsync() + { + while (true) + { + Task write; + lock (writeGate) write = pendingWrite; + await write.ConfigureAwait(false); + lock (writeGate) + if (ReferenceEquals(write, pendingWrite)) return; + } + } - return Task.FromResult(true); + private static bool WriteTags(string filePath, string[] tags, string[] names, IFileTagsStore? store) + { + try + { + GetDbInstance().SetTags(filePath, null, tags); + if (store is not null && !store.WriteTags(filePath, names)) + App.Logger?.LogDebug("Extended attributes are not available for '{FilePath}'; tags are kept in the database only.", LogPathHelper.RedactPath(filePath)); + return true; } - catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + catch (Exception ex) when (ex is not (OutOfMemoryException or StackOverflowException or AccessViolationException)) { - return Task.FromResult(false); + App.Logger?.LogWarning(ex, "Could not write file tags."); + return false; + } + } + + private static Task EnqueueWrite(Func action, T failureResult) + { + lock (writeGate) + { + var previous = pendingWrite; + var write = Task.Run(async () => + { + await previous.ConfigureAwait(false); + try + { + return action(); + } + catch (Exception ex) when (ex is not (OutOfMemoryException or StackOverflowException or AccessViolationException)) + { + App.Logger?.LogWarning(ex, "Could not write file tags."); + return failureResult; + } + }); + pendingWrite = write; + return write; } } diff --git a/src/Files.App/ViewModels/ShellViewModel.cs b/src/Files.App/ViewModels/ShellViewModel.cs index df9c96ac6255..42b1c1081724 100644 --- a/src/Files.App/ViewModels/ShellViewModel.cs +++ b/src/Files.App/ViewModels/ShellViewModel.cs @@ -1575,11 +1575,22 @@ private static bool HasPerFileIcon(string? extension) // Types whose icon is embedded in the file itself rather than shared by the extension private static readonly string[] _perFileIconExtensions = [".ico", ".cur", ".ani", ".scr", ".msc", ".appref-ms", ".desktop"]; + private static Task ReadFileTagAsync(string filePath) + { +#if WINDOWS + return Task.Run(() => FileTagsHelper.ReadFileTag(filePath)); +#else + return FileTagsHelper.ReadAndUpdateFileTagsAsync(filePath); +#endif + } + +#if WINDOWS private static void SetFileTag(ListedItem item) { var dbInstance = FileTagsHelper.GetDbInstance(); dbInstance.SetTags(item.GetRequiredPath(), item.FileFRN, item.FileTags ?? []); } +#endif // Loads extended file properties off the critical path so a slow per-file read never blocks the row's essentials. private async Task LoadExtendedFilePropertiesInBackgroundAsync(ListedItem item, BaseStorageFile file, CancellationToken token) @@ -1691,7 +1702,7 @@ public async Task LoadExtendedItemPropertiesAsync(ListedItem item) // A network share is never a cloud placeholder root, so skip that round-trip var syncStatus = isItemNetwork ? CloudDriveSyncStatus.Unknown : await CheckCloudDriveSyncStatusAsync(matchingStorageFile); var fileFRN = await FileTagsHelper.GetFileFRN(matchingStorageFile); - var fileTag = await Task.Run(() => FileTagsHelper.ReadFileTag(item.GetRequiredPath())); + var fileTag = await ReadFileTagAsync(item.GetRequiredPath()); // Extended properties open each file; load them in the background on a share var extraProperties = isItemNetwork ? null : await GetExtraProperties(matchingStorageFile); @@ -1736,7 +1747,9 @@ await dispatcherQueue.EnqueueOrInvokeAsync(() => }, Microsoft.UI.Dispatching.DispatcherQueuePriority.Low); +#if WINDOWS await Task.Run(() => SetFileTag(item)); +#endif if (isItemNetwork) _ = LoadExtendedFilePropertiesInBackgroundAsync(item, matchingStorageFile, token); @@ -1771,7 +1784,7 @@ await dispatcherQueue.EnqueueOrInvokeAsync(() => // A network share is never a cloud placeholder root, so skip that round-trip var syncStatus = isItemNetwork ? CloudDriveSyncStatus.Unknown : await CheckCloudDriveSyncStatusAsync(matchingStorageFolder); var fileFRN = await FileTagsHelper.GetFileFRN(matchingStorageFolder); - var fileTag = await Task.Run(() => FileTagsHelper.ReadFileTag(item.GetRequiredPath())); + var fileTag = await ReadFileTagAsync(item.GetRequiredPath()); // Folder extended properties only carry drive storage details, irrelevant on a network subfolder var extraProperties = isItemNetwork ? null : await GetExtraProperties(matchingStorageFolder); @@ -1800,7 +1813,9 @@ await dispatcherQueue.EnqueueOrInvokeAsync(() => }, Microsoft.UI.Dispatching.DispatcherQueuePriority.Low); +#if WINDOWS await Task.Run(() => SetFileTag(item)); +#endif wasSyncStatusLoaded = true; } } @@ -1819,7 +1834,7 @@ await dispatcherQueue.EnqueueOrInvokeAsync(() => token.ThrowIfCancellationRequested(); await FilesystemTasks.Wrap(async () => { - var fileTag = await Task.Run(() => FileTagsHelper.ReadFileTag(item.GetRequiredPath())); + var fileTag = await ReadFileTagAsync(item.GetRequiredPath()); await dispatcherQueue.EnqueueOrInvokeAsync(() => { @@ -1830,7 +1845,9 @@ await dispatcherQueue.EnqueueOrInvokeAsync(() => }, Microsoft.UI.Dispatching.DispatcherQueuePriority.Low); +#if WINDOWS await Task.Run(() => SetFileTag(item)); +#endif }); } else diff --git a/src/Files.App/Views/Layouts/BaseLayoutPage.cs b/src/Files.App/Views/Layouts/BaseLayoutPage.cs index 3c76aaff0d95..80f82aad1bc7 100644 --- a/src/Files.App/Views/Layouts/BaseLayoutPage.cs +++ b/src/Files.App/Views/Layouts/BaseLayoutPage.cs @@ -718,6 +718,9 @@ private CancellationToken RenewShellMenuToken() [DynamicWindowsRuntimeCast(typeof(MenuFlyout))] private async void ItemContextFlyout_Opening(object? sender, object e) { +#if !WINDOWS + using var trace = Files.Platform.Abstractions.Diagnostics.PerformanceTrace.Begin("context-menu-build", DispatcherQueue.HasThreadAccess); +#endif try { var parentShellPage = await EnsurePageIsCurrentAsync(); @@ -994,6 +997,9 @@ protected override void OnNavigatingFrom(NavigatingCancelEventArgs e) private async void BaseContextFlyout_Opening(object? sender, object e) { +#if !WINDOWS + using var trace = Files.Platform.Abstractions.Diagnostics.PerformanceTrace.Begin("context-menu-build", DispatcherQueue.HasThreadAccess); +#endif try { var parentShellPage = await EnsurePageIsCurrentAsync(); diff --git a/src/Files.App/Views/Shells/BaseShellPage.cs b/src/Files.App/Views/Shells/BaseShellPage.cs index b03292046f86..93c0724d75c6 100644 --- a/src/Files.App/Views/Shells/BaseShellPage.cs +++ b/src/Files.App/Views/Shells/BaseShellPage.cs @@ -576,7 +576,11 @@ public Task TabItemDrop(object sender, DragEventArgs e) public async Task RefreshIfNoWatcherExistsAsync() { var shellViewModel = this.GetRequiredShellViewModel(); - if (shellViewModel.HasNoWatcher) + if (shellViewModel.HasNoWatcher +#if !WINDOWS + || shellViewModel.IsLinuxWatcherPolling +#endif + ) await Refresh_Click(); } diff --git a/src/Files.Platform.Abstractions/Diagnostics/PerformanceTrace.cs b/src/Files.Platform.Abstractions/Diagnostics/PerformanceTrace.cs new file mode 100644 index 000000000000..0622f6539589 --- /dev/null +++ b/src/Files.Platform.Abstractions/Diagnostics/PerformanceTrace.cs @@ -0,0 +1,78 @@ +// Copyright (c) Files Community +// Licensed under the MIT License. + +using System; +using System.Diagnostics; +using System.Threading; +using System.Threading.Channels; +using System.Threading.Tasks; + +namespace Files.Platform.Abstractions.Diagnostics +{ + /// Opt-in, bounded performance records without paths, arguments or payloads. + public static class PerformanceTrace + { + public static bool Enabled { get; } = Environment.GetEnvironmentVariable("FILES_TRACE") == "1"; + private static readonly AsyncLocal current = new(); + private static readonly Channel? records = Enabled ? CreateChannel() : null; + private static long nextId; + + private readonly record struct Record(long Id, long Parent, string Operation, double Milliseconds, int Thread, bool? UiThread, string? Outcome); + + private static Channel CreateChannel() + { + var channel = Channel.CreateBounded(new BoundedChannelOptions(1024) + { + FullMode = BoundedChannelFullMode.DropWrite, + SingleReader = true, + }); + _ = Task.Run(async () => + { + await foreach (var record in channel.Reader.ReadAllAsync().ConfigureAwait(false)) + { + try + { + Console.Error.WriteLine(FormattableString.Invariant($"[files-trace] id={record.Id} parent={record.Parent} operation={record.Operation} ms={record.Milliseconds:F3} thread={record.Thread} ui={record.UiThread?.ToString() ?? "unknown"} outcome={record.Outcome ?? "completed-or-unwound"}")); + } + catch (System.IO.IOException) { } + } + }); + return channel; + } + + public static Scope Begin(string operation, bool? uiThread = null) + { + if (!Enabled) return default; + var parent = current.Value; + var id = Interlocked.Increment(ref nextId); + current.Value = id; + return new Scope(id, parent, operation, uiThread); + } + + public readonly struct Scope : IDisposable + { + private readonly long id, parent, start; + private readonly string? operation; + private readonly bool? uiThread; + + internal Scope(long id, long parent, string operation, bool? uiThread) + { + this.id = id; + this.parent = parent; + this.operation = operation; + this.uiThread = uiThread; + start = Stopwatch.GetTimestamp(); + } + + public void Dispose() => Complete(null); + + public void Complete(string? outcome) + { + if (operation is null) return; + current.Value = parent; + records?.Writer.TryWrite(new Record(id, parent, operation, Stopwatch.GetElapsedTime(start).TotalMilliseconds, + Environment.CurrentManagedThreadId, uiThread, outcome)); + } + } + } +} diff --git a/src/Files.Platform.Linux/Archives/ISevenZipRunner.cs b/src/Files.Platform.Linux/Archives/ISevenZipRunner.cs index 6bf0ce75904e..d09058b514c9 100644 --- a/src/Files.Platform.Linux/Archives/ISevenZipRunner.cs +++ b/src/Files.Platform.Linux/Archives/ISevenZipRunner.cs @@ -80,7 +80,7 @@ public SevenZipProcessRunner(IExecutableLocator locator) foreach (var argument in arguments) startInfo.ArgumentList.Add(argument); - using var process = Process.Start(startInfo) ?? throw new InvalidOperationException("The 7-Zip process could not be started."); + using var process = Files.Platform.Linux.Launching.TracedProcess.Start(startInfo) ?? throw new InvalidOperationException("The 7-Zip process could not be started."); process.StandardInput.Close(); var output = new StringBuilder(); diff --git a/src/Files.Platform.Linux/DBus/DBusPerformanceExtensions.cs b/src/Files.Platform.Linux/DBus/DBusPerformanceExtensions.cs new file mode 100644 index 000000000000..3a37911042b4 --- /dev/null +++ b/src/Files.Platform.Linux/DBus/DBusPerformanceExtensions.cs @@ -0,0 +1,50 @@ +// Copyright (c) Files Community +// Licensed under the MIT License. + +using Files.Platform.Abstractions.Diagnostics; +using System; +using System.Threading.Tasks; +using Tmds.DBus.Protocol; + +namespace Files.Platform.Linux.DBus +{ + internal static class DBusPerformanceExtensions + { + public static Task CallTracedAsync(this DBusConnection bus, string operation, MessageBuffer message, MessageValueReader reader, object? state) + => PerformanceTrace.Enabled ? TraceAsync(operation, bus.CallMethodAsync(message, reader, state)) : bus.CallMethodAsync(message, reader, state); + + public static Task CallTracedAsync(this DBusConnection bus, string operation, MessageBuffer message) + => PerformanceTrace.Enabled ? TraceAsync(operation, bus.CallMethodAsync(message)) : bus.CallMethodAsync(message); + + private static async Task TraceAsync(string operation, Task call) + { + var trace = PerformanceTrace.Begin(operation); + try + { + var result = await call.ConfigureAwait(false); + trace.Complete("reply"); + return result; + } + catch + { + trace.Complete("fault"); + throw; + } + } + + private static async Task TraceAsync(string operation, Task call) + { + var trace = PerformanceTrace.Begin(operation); + try + { + await call.ConfigureAwait(false); + trace.Complete("reply"); + } + catch + { + trace.Complete("fault"); + throw; + } + } + } +} diff --git a/src/Files.Platform.Linux/DBus/DBusSession.cs b/src/Files.Platform.Linux/DBus/DBusSession.cs index 988022b78954..e0be19a2fae8 100644 --- a/src/Files.Platform.Linux/DBus/DBusSession.cs +++ b/src/Files.Platform.Linux/DBus/DBusSession.cs @@ -17,6 +17,7 @@ public static class DBusSession /// public static async Task TryConnectAsync(string? address, TimeSpan timeout) { + using var trace = Files.Platform.Abstractions.Diagnostics.PerformanceTrace.Begin("dbus-connect"); address ??= DBusAddress.Session; if (string.IsNullOrEmpty(address)) return null; diff --git a/src/Files.Platform.Linux/Elevation/PkexecElevationService.cs b/src/Files.Platform.Linux/Elevation/PkexecElevationService.cs index 8aec117b86e2..7720419ff075 100644 --- a/src/Files.Platform.Linux/Elevation/PkexecElevationService.cs +++ b/src/Files.Platform.Linux/Elevation/PkexecElevationService.cs @@ -47,7 +47,7 @@ public sealed class ProcessElevatedRunner(Action? terminate = null) : I foreach (var argument in arguments) startInfo.ArgumentList.Add(argument); - using var process = Process.Start(startInfo) ?? throw new InvalidOperationException("The process could not be started."); + using var process = Files.Platform.Linux.Launching.TracedProcess.Start(startInfo) ?? throw new InvalidOperationException("The process could not be started."); process.StandardInput.Close(); var stdout = process.StandardOutput.ReadToEndAsync(cancellationToken); var stderr = process.StandardError.ReadToEndAsync(cancellationToken); @@ -91,7 +91,7 @@ private static void TryKill(Process process, Action? terminate) info.Environment["LANG"] = "C"; info.ArgumentList.Add(ElevationHelperProtocol.HelperPath); foreach (var argument in HelperAuthorization.Arguments(json)) info.ArgumentList.Add(argument); - using var process = Process.Start(info) ?? throw new IOException("Unable to start authorization."); + using var process = Files.Platform.Linux.Launching.TracedProcess.Start(info) ?? throw new IOException("Unable to start authorization."); var output = ReadBoundedAsync(process.StandardOutput, CancellationToken.None, Stop); var error = ReadBoundedAsync(process.StandardError, CancellationToken.None, Stop); var send = SendAsync(); diff --git a/src/Files.Platform.Linux/Enumeration/LinuxFileSystemEnumerator.cs b/src/Files.Platform.Linux/Enumeration/LinuxFileSystemEnumerator.cs index 8006cab12d81..b135f4153bfa 100644 --- a/src/Files.Platform.Linux/Enumeration/LinuxFileSystemEnumerator.cs +++ b/src/Files.Platform.Linux/Enumeration/LinuxFileSystemEnumerator.cs @@ -37,6 +37,7 @@ public async IAsyncEnumerable> EnumerateBatch FileSystemEnumerationOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) { + using var trace = Files.Platform.Abstractions.Diagnostics.PerformanceTrace.Begin("folder-enumeration"); ArgumentException.ThrowIfNullOrEmpty(folderPath); options ??= new(); var batchSize = Math.Max(1, options.BatchSize); @@ -65,6 +66,7 @@ public async IAsyncEnumerable> EnumerateBatch private static List ReadBatch(IEnumerator enumerator, int batchSize, CancellationToken cancellationToken) { + using var trace = Files.Platform.Abstractions.Diagnostics.PerformanceTrace.Begin("folder-enumeration-batch", false); var batch = new List(batchSize); while (batch.Count < batchSize && enumerator.MoveNext()) { diff --git a/src/Files.Platform.Linux/FileChooser/PortalFileChooserService.cs b/src/Files.Platform.Linux/FileChooser/PortalFileChooserService.cs index 0eddc1075d22..5e2e69adbf1b 100644 --- a/src/Files.Platform.Linux/FileChooser/PortalFileChooserService.cs +++ b/src/Files.Platform.Linux/FileChooser/PortalFileChooserService.cs @@ -76,7 +76,7 @@ public async Task ChooseAsync(FileChooserRequest request, Can writer.Dispose(); } - handlePath = await bus.CallMethodAsync(message, static (Message m, object? _) => m.GetBodyReader().ReadObjectPathAsString(), null).WaitAsync(CallTimeout, cancellationToken).ConfigureAwait(false); + handlePath = await bus.CallTracedAsync("dbus.filechooser", message, static (Message m, object? _) => m.GetBodyReader().ReadObjectPathAsString(), null).WaitAsync(CallTimeout, cancellationToken).ConfigureAwait(false); // Older portals may not honor handle_token; the returned handle is authoritative var returnedToken = handlePath[(handlePath.LastIndexOf('/') + 1)..]; diff --git a/src/Files.Platform.Linux/Gvfs/GioRunner.cs b/src/Files.Platform.Linux/Gvfs/GioRunner.cs index c857ceff02ac..683b0729f3e6 100644 --- a/src/Files.Platform.Linux/Gvfs/GioRunner.cs +++ b/src/Files.Platform.Linux/Gvfs/GioRunner.cs @@ -73,7 +73,7 @@ public async Task RunAsync(IReadOnlyList arguments, Cancellat try { - using var process = Process.Start(startInfo); + using var process = Files.Platform.Linux.Launching.TracedProcess.Start(startInfo); if (process is null) return new GioResult(-1, "gio could not be started."); diff --git a/src/Files.Platform.Linux/Instance/LinuxSingleInstanceService.cs b/src/Files.Platform.Linux/Instance/LinuxSingleInstanceService.cs index 43520449ada8..c6e922c37df8 100644 --- a/src/Files.Platform.Linux/Instance/LinuxSingleInstanceService.cs +++ b/src/Files.Platform.Linux/Instance/LinuxSingleInstanceService.cs @@ -199,7 +199,7 @@ private async Task TryBecomePrimaryOnBusAsync(DBusConnection bus, Instance // Somebody else owns the name: hand over the command line var message = BuildLaunch(bus, path, launchRequest); - await bus.CallMethodAsync(message).WaitAsync(ForwardTimeout, cancellationToken).ConfigureAwait(false); + await bus.CallTracedAsync("dbus.instance", message).WaitAsync(ForwardTimeout, cancellationToken).ConfigureAwait(false); bus.Dispose(); return false; } diff --git a/src/Files.Platform.Linux/Launching/IProcessStarter.cs b/src/Files.Platform.Linux/Launching/IProcessStarter.cs index ffaafd533515..dac841ef699a 100644 --- a/src/Files.Platform.Linux/Launching/IProcessStarter.cs +++ b/src/Files.Platform.Linux/Launching/IProcessStarter.cs @@ -93,13 +93,14 @@ public async Task StartDetachedAsync(ProcessLaunch launch, CancellationToken can foreach (var argument in launch.Arguments) startInfo.ArgumentList.Add(argument); - using var process = Process.Start(startInfo) + using var process = Files.Platform.Linux.Launching.TracedProcess.Start(startInfo) ?? throw new InvalidOperationException("The process could not be started."); process.StandardInput.Close(); process.StandardOutput.Close(); process.StandardError.Close(); + using var trace = Files.Platform.Abstractions.Diagnostics.PerformanceTrace.Begin("process-wrapper-exit"); await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false); } } diff --git a/src/Files.Platform.Linux/Launching/RootTerminalResolver.cs b/src/Files.Platform.Linux/Launching/RootTerminalResolver.cs index 2f7e097e6e48..d47a275e895b 100644 --- a/src/Files.Platform.Linux/Launching/RootTerminalResolver.cs +++ b/src/Files.Platform.Linux/Launching/RootTerminalResolver.cs @@ -72,7 +72,7 @@ public static bool SupportsKeepCwd(string? output) info.Environment.Clear(); info.Environment["LANG"] = "C"; info.ArgumentList.Add("--version"); - using var process = Process.Start(info); + using var process = Files.Platform.Linux.Launching.TracedProcess.Start(info); if (process is null) return null; var output = process.StandardOutput.ReadToEndAsync(); var error = process.StandardError.ReadToEndAsync(); diff --git a/src/Files.Platform.Linux/Launching/TracedProcess.cs b/src/Files.Platform.Linux/Launching/TracedProcess.cs new file mode 100644 index 000000000000..1a87438560ea --- /dev/null +++ b/src/Files.Platform.Linux/Launching/TracedProcess.cs @@ -0,0 +1,17 @@ +// Copyright (c) Files Community +// Licensed under the MIT License. + +using Files.Platform.Abstractions.Diagnostics; +using System.Diagnostics; + +namespace Files.Platform.Linux.Launching +{ + internal static class TracedProcess + { + public static Process? Start(ProcessStartInfo info) + { + using var trace = PerformanceTrace.Begin("process-spawn"); + return Process.Start(info); + } + } +} diff --git a/src/Files.Platform.Linux/Mime/LinuxApplicationRegistry.cs b/src/Files.Platform.Linux/Mime/LinuxApplicationRegistry.cs index 0843ace2d613..286f57e7aa12 100644 --- a/src/Files.Platform.Linux/Mime/LinuxApplicationRegistry.cs +++ b/src/Files.Platform.Linux/Mime/LinuxApplicationRegistry.cs @@ -2,6 +2,7 @@ // Licensed under the MIT License. using Files.Platform.Abstractions.Mime; +using Files.Platform.Abstractions.Diagnostics; using Files.Platform.Linux.Launching; using System; using System.Collections.Generic; @@ -22,6 +23,9 @@ public sealed class LinuxApplicationRegistry : IApplicationRegistry private readonly CultureInfo culture; private readonly IExecutableLocator locator; private readonly MimeHierarchy hierarchy; + private readonly ParsedFileCache desktopEntries = new(); + private readonly ParsedFileCache associations = new(); + private readonly ParsedFileCache> mimeInfo = new(); /// /// Creates the registry for the process environment. @@ -44,86 +48,102 @@ public LinuxApplicationRegistry(XdgDirectories xdg, CultureInfo culture, IExecut /// public Task> GetApplicationsForMimeTypeAsync(string mimeType, CancellationToken cancellationToken = default) { - cancellationToken.ThrowIfCancellationRequested(); - - var apps = new List(); - var seen = new HashSet(StringComparer.Ordinal); - foreach (var type in hierarchy.GetChain(mimeType)) + return Task.Run>(() => { - var (_, all) = BuildCandidates(type); - foreach (var id in all) + using var trace = PerformanceTrace.Begin("open-with-query", false); + cancellationToken.ThrowIfCancellationRequested(); + + var apps = new List(); + var seen = new HashSet(StringComparer.Ordinal); + foreach (var type in hierarchy.GetChain(mimeType)) { - if (!seen.Add(id)) - continue; + var (_, all) = BuildCandidates(type); + foreach (var id in all) + { + if (!seen.Add(id)) + continue; - var app = Load(id); - if (app is not null && !app.NoDisplay) - apps.Add(app); + var app = Load(id); + if (app is not null && !app.NoDisplay) + apps.Add(app); + } } - } - return Task.FromResult>(apps); + return (IReadOnlyList)apps; + }, cancellationToken); } /// public Task> GetAllApplicationsAsync(CancellationToken cancellationToken = default) { - var apps = new List(); - var seen = new HashSet(StringComparer.Ordinal); - foreach (var dir in xdg.AllDataDirs) + return Task.Run>(() => { - cancellationToken.ThrowIfCancellationRequested(); - var applications = Path.Combine(dir, "applications"); - if (!Directory.Exists(applications)) - continue; - - foreach (var (id, _) in EnumerateDesktopFiles(applications)) + using var trace = PerformanceTrace.Begin("open-with-query", false); + var apps = new List(); + var seen = new HashSet(StringComparer.Ordinal); + foreach (var dir in xdg.AllDataDirs) { - if (!seen.Add(id)) + cancellationToken.ThrowIfCancellationRequested(); + var applications = Path.Combine(dir, "applications"); + if (!Directory.Exists(applications)) continue; - var app = Load(id); - if (app is not null && !app.NoDisplay) - apps.Add(app); + foreach (var (id, _) in EnumerateDesktopFiles(applications)) + { + if (!seen.Add(id)) + continue; + + var app = Load(id); + if (app is not null && !app.NoDisplay) + apps.Add(app); + } } - } - apps.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.CurrentCultureIgnoreCase)); - return Task.FromResult>(apps); + apps.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.CurrentCultureIgnoreCase)); + return (IReadOnlyList)apps; + }, cancellationToken); } /// public Task GetDefaultApplicationAsync(string mimeType, CancellationToken cancellationToken = default) { - cancellationToken.ThrowIfCancellationRequested(); - - // Per type, nearest first: the explicit default, else the first visible association (like xdg-open) - foreach (var type in hierarchy.GetChain(mimeType)) + return Task.Run(() => { - var (defaults, all) = BuildCandidates(type); - foreach (var id in defaults) - { - var app = Load(id); - if (app is not null) - return Task.FromResult(app); - } + using var trace = PerformanceTrace.Begin("open-with-query", false); + cancellationToken.ThrowIfCancellationRequested(); - foreach (var id in all) + // Per type, nearest first: the explicit default, else the first visible association (like xdg-open) + foreach (var type in hierarchy.GetChain(mimeType)) { - var app = Load(id); - if (app is not null && !app.NoDisplay) - return Task.FromResult(app); + var (defaults, all) = BuildCandidates(type); + foreach (var id in defaults) + { + var app = Load(id); + if (app is not null) + return app; + } + + foreach (var id in all) + { + var app = Load(id); + if (app is not null && !app.NoDisplay) + return app; + } } - } - return Task.FromResult(null); + return (DesktopApplication?)null; + }, cancellationToken); } /// public Task GetApplicationAsync(string desktopId, CancellationToken cancellationToken = default) { - cancellationToken.ThrowIfCancellationRequested(); - return Task.FromResult(Load(desktopId)); + return Task.Run(() => + { + using var trace = PerformanceTrace.Begin("open-with-query", false); + cancellationToken.ThrowIfCancellationRequested(); + return Load(desktopId); + }, cancellationToken); } /// @@ -189,7 +209,7 @@ void Add(List list, string id) foreach (var file in MimeAppsListFiles()) { - var list = MimeAppsList.Load(file); + var list = associations.Get(file, MimeAppsList.Load); if (list is null) continue; @@ -223,37 +243,21 @@ void Add(List list, string id) private IEnumerable ReadMimeInfoCache(string mimeType) { - var prefix = mimeType + "="; foreach (var dir in xdg.AllDataDirs) { var applications = Path.Combine(dir, "applications"); var cache = Path.Combine(applications, "mimeinfo.cache"); - if (File.Exists(cache)) { - string[] lines; - try - { - lines = File.ReadAllLines(cache); - } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) - { - continue; - } - - var line = lines.FirstOrDefault(l => l.StartsWith(prefix, StringComparison.Ordinal)); - if (line is not null) - { - foreach (var id in DesktopEntryParser.SplitList(line[prefix.Length..])) - yield return id; - } + var mapping = mimeInfo.Get(cache, ReadMimeInfo); + if (mapping?.TryGetValue(mimeType, out var ids) == true) + foreach (var id in ids) yield return id; } else if (Directory.Exists(applications)) { - // Cache not generated: scan the desktop files directly foreach (var (id, file) in EnumerateDesktopFiles(applications)) { - var entry = DesktopEntryParser.ParseFile(file, id, culture); + var entry = desktopEntries.Get(file, p => DesktopEntryParser.ParseFile(p, id, culture)); if (entry?.Application.MimeTypes?.Contains(mimeType) == true) yield return id; } @@ -261,6 +265,25 @@ private IEnumerable ReadMimeInfoCache(string mimeType) } } + private static Dictionary? ReadMimeInfo(string path) + { + try + { + var result = new Dictionary(StringComparer.Ordinal); + foreach (var line in File.ReadLines(path)) + { + var eq = line.IndexOf('='); + if (eq > 0) + result.TryAdd(line[..eq], DesktopEntryParser.SplitList(line[(eq + 1)..])); + } + return result; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return null; + } + } + private static IEnumerable<(string Id, string Path)> EnumerateDesktopFiles(string applicationsDir) { IEnumerable files; @@ -287,7 +310,7 @@ private IEnumerable ReadMimeInfoCache(string mimeType) if (!File.Exists(candidate)) continue; - var entry = DesktopEntryParser.ParseFile(candidate, desktopId, culture); + var entry = desktopEntries.Get(candidate, p => DesktopEntryParser.ParseFile(p, desktopId, culture)); if (entry is null || entry.Hidden) return null; diff --git a/src/Files.Platform.Linux/Mime/LinuxServiceMenuService.cs b/src/Files.Platform.Linux/Mime/LinuxServiceMenuService.cs index d9fda36c686b..0723dd0d33cc 100644 --- a/src/Files.Platform.Linux/Mime/LinuxServiceMenuService.cs +++ b/src/Files.Platform.Linux/Mime/LinuxServiceMenuService.cs @@ -2,6 +2,7 @@ // Licensed under the MIT License. using Files.Platform.Abstractions.Mime; +using Files.Platform.Abstractions.Diagnostics; using Files.Platform.Linux.Launching; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; @@ -25,6 +26,7 @@ public sealed class LinuxServiceMenuService : IServiceMenuService private readonly IMimeTypeService mimeTypes; private readonly CultureInfo culture; private readonly MimeHierarchy hierarchy; + private readonly ParsedFileCache menus = new(followLinks: false); private readonly ILogger logger; public LinuxServiceMenuService(XdgDirectories directories, IMimeTypeService mimeTypes, CultureInfo culture, ILogger? logger = null) @@ -53,6 +55,7 @@ public async Task> GetActionsAsync(IReadOnlyLis private IReadOnlyList Scan(IReadOnlyList targets, IReadOnlyList types, CancellationToken cancellationToken) { + using var trace = PerformanceTrace.Begin("service-menu-scan", false); var result = new List(); var seen = new HashSet(StringComparer.Ordinal); var scanned = 0; @@ -73,7 +76,7 @@ private IReadOnlyList Scan(IReadOnlyList targets, IRe if (!path.EndsWith(".desktop", StringComparison.Ordinal) || !seen.Add(Path.GetFileName(path))) continue; try { - var menu = Read(path, culture, out _, logger); + var menu = menus.Get(path, p => Read(p, culture, out _, logger)); if (menu is null || !menu.Matches(targets, types, hierarchy)) continue; result.AddRange(menu.Actions.Where(a => DesktopExecExpander.ExpandServiceMenu(a.Application, targets).Count > 0) .Take(MaxActions - result.Count)); diff --git a/src/Files.Platform.Linux/Mime/ParsedFileCache.cs b/src/Files.Platform.Linux/Mime/ParsedFileCache.cs new file mode 100644 index 000000000000..ea26c7bacf75 --- /dev/null +++ b/src/Files.Platform.Linux/Mime/ParsedFileCache.cs @@ -0,0 +1,55 @@ +// Copyright (c) Files Community +// Licensed under the MIT License. + +using Files.Platform.Abstractions.Diagnostics; +using Files.Platform.Linux.Native; +using System; +using System.Collections.Generic; + +namespace Files.Platform.Linux.Mime +{ + /// Reuses parsing until a file's device, inode, mode, size or nanosecond mtime or ctime changes. + internal sealed class ParsedFileCache where T : class + { + private readonly object gate = new(); + private readonly Dictionary entries = new(StringComparer.Ordinal); + private readonly bool followLinks; + + public ParsedFileCache(bool followLinks = true) => this.followLinks = followLinks; + + public T? Get(string path, Func read) + { + lock (gate) + { + var trace = PerformanceTrace.Begin("parsed-file-cache", false); + var flags = followLinks ? 0 : PosixNative.AtSymlinkNofollow; + if (!PosixNative.TryStat(PosixNative.AtFdCwd, path, flags, out var stamp) || !stamp.IsRegularFile) + { + entries.Remove(path); + trace.Complete("missing-or-unreadable"); + return null; + } + if (entries.TryGetValue(path, out var entry) && entry.Stamp == stamp) + { + trace.Complete("hit"); + return entry.Value; + } + var value = read(path); + if (PosixNative.TryStat(PosixNative.AtFdCwd, path, flags, out var after) && after == stamp) + { + if (value is not null) + { + if (entries.Count >= 4096) entries.Clear(); + entries[path] = (stamp, value); + } + else + entries.Remove(path); + } + else + value = null; + trace.Complete("miss"); + return value; + } + } + } +} diff --git a/src/Files.Platform.Linux/Native/PosixNative.cs b/src/Files.Platform.Linux/Native/PosixNative.cs index 8c68524c7214..37819abb5425 100644 --- a/src/Files.Platform.Linux/Native/PosixNative.cs +++ b/src/Files.Platform.Linux/Native/PosixNative.cs @@ -15,7 +15,7 @@ namespace Files.Platform.Linux.Native /// Mount-related statx fields: attribute bits with their support mask, the mount id (when reported) and the device. public readonly record struct MountInfo(ulong Attributes, ulong AttributesMask, bool MountIdValid, ulong MountId, uint DevMajor, uint DevMinor); - internal readonly record struct PosixStat(uint Mode, ulong Size, uint OwnerUserId, long ModifiedSeconds, uint ModifiedNanoseconds, ulong Inode = 0, uint DevMajor = 0, uint DevMinor = 0, ulong? MountId = null) + internal readonly record struct PosixStat(uint Mode, ulong Size, uint OwnerUserId, long ModifiedSeconds, uint ModifiedNanoseconds, ulong Inode = 0, uint DevMajor = 0, uint DevMinor = 0, ulong? MountId = null, long ChangedSeconds = 0, uint ChangedNanoseconds = 0) { public uint FileType => Mode & 0xF000; @@ -47,6 +47,7 @@ internal static unsafe partial class PosixNative private const uint StatxMode = 0x2; private const uint StatxUid = 0x8; private const uint StatxMtime = 0x40; + private const uint StatxCtime = 0x80; private const uint StatxIno = 0x100; private const uint StatxSize = 0x200; private const uint StatxMountId = 0x1000; @@ -88,7 +89,7 @@ public static bool TryStat(int dirfd, string path, int flags, out PosixStat stat try { - const uint mask = StatxType | StatxMode | StatxUid | StatxMtime | StatxSize | StatxIno | StatxMountId; + const uint mask = StatxType | StatxMode | StatxUid | StatxMtime | StatxCtime | StatxSize | StatxIno | StatxMountId; if (!TryStatx(dirfd, path, flags, mask, out var buffer, out errno)) return false; @@ -103,7 +104,9 @@ public static bool TryStat(int dirfd, string path, int flags, out PosixStat stat stat = new PosixStat(BitConverter.ToUInt16(buffer, 28), size, BitConverter.ToUInt32(buffer, 20), seconds, nanos, (returned & StatxIno) != 0 ? BitConverter.ToUInt64(buffer, 32) : 0, BitConverter.ToUInt32(buffer, 136), BitConverter.ToUInt32(buffer, 140), - (returned & StatxMountId) != 0 ? BitConverter.ToUInt64(buffer, 144) : null); + (returned & StatxMountId) != 0 ? BitConverter.ToUInt64(buffer, 144) : null, + (returned & StatxCtime) != 0 ? BitConverter.ToInt64(buffer, 96) : 0, + (returned & StatxCtime) != 0 ? BitConverter.ToUInt32(buffer, 104) : 0); return true; } catch (Exception ex) when (ex is DllNotFoundException or EntryPointNotFoundException) diff --git a/src/Files.Platform.Linux/Notifications/DBusNotificationService.cs b/src/Files.Platform.Linux/Notifications/DBusNotificationService.cs index 7915ffffdd07..d203e4e36185 100644 --- a/src/Files.Platform.Linux/Notifications/DBusNotificationService.cs +++ b/src/Files.Platform.Linux/Notifications/DBusNotificationService.cs @@ -44,7 +44,7 @@ public async Task NotifyAsync(string title, string body, CancellationToken var message = BuildNotify(bus, title, body); - await bus.CallMethodAsync(message, static (Message m, object? _) => m.GetBodyReader().ReadUInt32(), null) + await bus.CallTracedAsync("dbus.notifications", message, static (Message m, object? _) => m.GetBodyReader().ReadUInt32(), null) .WaitAsync(CallTimeout, cancellationToken).ConfigureAwait(false); return true; } diff --git a/src/Files.Platform.Linux/Secrets/SecretServiceStore.cs b/src/Files.Platform.Linux/Secrets/SecretServiceStore.cs index b6d698d557ef..b971f05ac684 100644 --- a/src/Files.Platform.Linux/Secrets/SecretServiceStore.cs +++ b/src/Files.Platform.Linux/Secrets/SecretServiceStore.cs @@ -151,7 +151,7 @@ private static Task OpenSessionAsync(DBusConnection bus) writer.WriteMethodCallHeader(Service, ServicePath, ServiceInterface, "OpenSession", "sv"); writer.WriteString("plain"); writer.WriteVariantString(string.Empty); - return bus.CallMethodAsync(writer.CreateMessage(), static (Message m, object? _) => + return bus.CallTracedAsync("dbus.secrets", writer.CreateMessage(), static (Message m, object? _) => { var reader = m.GetBodyReader(); reader.ReadVariantValue(); @@ -188,7 +188,7 @@ private static void WriteAttributes(ref MessageWriter writer, string resource, s } } - var (unlocked, locked) = await bus.CallMethodAsync(message, static (Message m, object? _) => + var (unlocked, locked) = await bus.CallTracedAsync("dbus.secrets", message, static (Message m, object? _) => { var reader = m.GetBodyReader(); var unlockedItems = reader.ReadArrayOfObjectPath().Select(p => p.ToString()).ToArray(); @@ -215,7 +215,7 @@ private static void WriteAttributes(ref MessageWriter writer, string resource, s message = writer.CreateMessage(); } - var bytes = await bus.CallMethodAsync(message, static (Message m, object? _) => + var bytes = await bus.CallTracedAsync("dbus.secrets", message, static (Message m, object? _) => { var reader = m.GetBodyReader(); reader.AlignStruct(); @@ -265,7 +265,7 @@ private static async Task SaveAsync(DBusConnection bus, string resource, s } } - var prompt = await bus.CallMethodAsync(message, static (Message m, object? _) => + var prompt = await bus.CallTracedAsync("dbus.secrets", message, static (Message m, object? _) => { var reader = m.GetBodyReader(); reader.ReadObjectPath(); @@ -298,7 +298,7 @@ private static async Task SaveAsync(DBusConnection bus, string resource, s message = writer.CreateMessage(); } - var prompt = await bus.CallMethodAsync(message, static (Message m, object? _) => m.GetBodyReader().ReadObjectPathAsString(), null).ConfigureAwait(false); + var prompt = await bus.CallTracedAsync("dbus.secrets", message, static (Message m, object? _) => m.GetBodyReader().ReadObjectPathAsString(), null).ConfigureAwait(false); return prompt == "/" ? "deleted" : "failed"; } } diff --git a/src/Files.Platform.Linux/Theme/LinuxColorScheme.cs b/src/Files.Platform.Linux/Theme/LinuxColorScheme.cs index aaae9973a528..84dd657dcc63 100644 --- a/src/Files.Platform.Linux/Theme/LinuxColorScheme.cs +++ b/src/Files.Platform.Linux/Theme/LinuxColorScheme.cs @@ -2,6 +2,7 @@ // Licensed under the MIT License. using System; +using Files.Platform.Linux.DBus; using System.Diagnostics; using System.IO; using System.Threading; @@ -90,7 +91,7 @@ private static async Task ReadPortalAsync() if (connection is null) return; - _lastRead = await connection.CallMethodAsync(BuildReadMessage(connection), static (Message message, object? _) => + _lastRead = await connection.CallTracedAsync("dbus.theme", BuildReadMessage(connection), static (Message message, object? _) => { var reader = message.GetBodyReader(); var outer = reader.ReadVariantValue(); @@ -241,7 +242,7 @@ await connection.AddMatchAsync(rule, static (Message message, object? _) => UseShellExecute = false, }; - using var process = Process.Start(info); + using var process = Files.Platform.Linux.Launching.TracedProcess.Start(info); if (process is null) return null; diff --git a/src/Files.Platform.Linux/Thumbnails/ExternalThumbnailers.cs b/src/Files.Platform.Linux/Thumbnails/ExternalThumbnailers.cs index 55766f1d72e9..b7ed9418daa5 100644 --- a/src/Files.Platform.Linux/Thumbnails/ExternalThumbnailers.cs +++ b/src/Files.Platform.Linux/Thumbnails/ExternalThumbnailers.cs @@ -324,7 +324,7 @@ public async Task RunAsync(string fileName, IReadOnlyList argument Process? process; try { - process = Process.Start(info); + process = Files.Platform.Linux.Launching.TracedProcess.Start(info); } catch (System.ComponentModel.Win32Exception) { diff --git a/src/Files.Platform.Linux/Volumes/UDisks2VolumeService.cs b/src/Files.Platform.Linux/Volumes/UDisks2VolumeService.cs index 52931377d6c8..fd077416c2f1 100644 --- a/src/Files.Platform.Linux/Volumes/UDisks2VolumeService.cs +++ b/src/Files.Platform.Linux/Volumes/UDisks2VolumeService.cs @@ -273,7 +273,7 @@ private async Task CallAsync(string path, string iface, string member, Mes try { - var result = await bus.CallMethodAsync(message, reader, null).WaitAsync(CallTimeout, cancellationToken).ConfigureAwait(false); + var result = await bus.CallTracedAsync("dbus.volumes", message, reader, null).WaitAsync(CallTimeout, cancellationToken).ConfigureAwait(false); await Task.Yield(); return result; } @@ -294,7 +294,7 @@ private async Task GetObjectsAsync(CancellationToken cancellatio message = writer.CreateMessage(); } - var objects = await bus.CallMethodAsync(message, static (Message m, object? _) => + var objects = await bus.CallTracedAsync("dbus.volumes", message, static (Message m, object? _) => { var reader = m.GetBodyReader(); return UDisks2Objects.Read(ref reader); diff --git a/src/Files.Platform.Linux/Wallpaper/PortalWallpaperService.cs b/src/Files.Platform.Linux/Wallpaper/PortalWallpaperService.cs index 32f5c15a50d0..6ed296940ead 100644 --- a/src/Files.Platform.Linux/Wallpaper/PortalWallpaperService.cs +++ b/src/Files.Platform.Linux/Wallpaper/PortalWallpaperService.cs @@ -59,7 +59,7 @@ public async Task IsAvailableAsync(CancellationToken cancellationToken = d message = writer.CreateMessage(); } - await bus.CallMethodAsync(message, static (Message _, object? _) => true, null).WaitAsync(CallTimeout, cancellationToken).ConfigureAwait(false); + await bus.CallTracedAsync("dbus.wallpaper", message, static (Message _, object? _) => true, null).WaitAsync(CallTimeout, cancellationToken).ConfigureAwait(false); return true; } catch (Exception ex) when (IsBackendFailure(ex)) @@ -103,7 +103,7 @@ public async Task SetAsync(string imagePath, WallpaperTarget ta message = writer.CreateMessage(); } - await bus.CallMethodAsync(message, static (Message _, object? _) => true, null).WaitAsync(CallTimeout, cancellationToken).ConfigureAwait(false); + await bus.CallTracedAsync("dbus.wallpaper", message, static (Message _, object? _) => true, null).WaitAsync(CallTimeout, cancellationToken).ConfigureAwait(false); uint code; try diff --git a/src/Files.Platform.Linux/Watching/LinuxFolderWatcher.cs b/src/Files.Platform.Linux/Watching/LinuxFolderWatcher.cs index d5b97e00c74c..b24a0d47682f 100644 --- a/src/Files.Platform.Linux/Watching/LinuxFolderWatcher.cs +++ b/src/Files.Platform.Linux/Watching/LinuxFolderWatcher.cs @@ -8,6 +8,7 @@ using System.Threading; using System.Threading.Tasks; using Files.Platform.Abstractions.Watching; +using Microsoft.Extensions.Logging; namespace Files.Platform.Linux.Watching { @@ -31,6 +32,8 @@ private enum ChangeKind { Created, Deleted, Changed, Renamed } private Timer? _debounceTimer; private bool _started; private bool _disposed; + private bool _pollingLogged; + private readonly ILogger logger; public event EventHandler? Created; public event EventHandler? Deleted; @@ -43,10 +46,11 @@ private enum ChangeKind { Created, Deleted, Changed, Renamed } public bool IsPolling => _pollCts is not null; - public LinuxFolderWatcher(string folderPath, FolderWatcherOptions options) + public LinuxFolderWatcher(string folderPath, FolderWatcherOptions options, ILogger logger) { FolderPath = folderPath; _options = options; + this.logger = logger; } public void Start() @@ -65,7 +69,10 @@ public void Start() try { if (_options.ForcePolling) + { StartPolling(); + LogPolling(null); + } else StartNative(); } @@ -81,7 +88,10 @@ public void Start() } if (nativeFailure is not null) + { + LogPolling(nativeFailure); Error?.Invoke(this, new FolderWatcherErrorEventArgs(nativeFailure, fellBackToPolling: true)); + } } public void Stop() @@ -163,9 +173,22 @@ private void OnWatcherError(object sender, ErrorEventArgs e) } } + if (fellBack) LogPolling(ex); Error?.Invoke(this, new FolderWatcherErrorEventArgs(ex, fellBack)); } + private void LogPolling(Exception? failure) + { + lock (_gate) + { + if (_pollingLogged) return; + _pollingLogged = true; + } + logger.LogWarning("Folder watcher is using fallback polling (interval {IntervalMs} ms, reason {Reason}); native failures can indicate inotify limits.", + (_options.PollInterval > TimeSpan.Zero ? _options.PollInterval : TimeSpan.FromSeconds(2)).TotalMilliseconds, + failure?.GetType().Name ?? "forced polling"); + } + private void StartPolling() { var cts = new CancellationTokenSource(); diff --git a/src/Files.Platform.Linux/Watching/LinuxFolderWatcherFactory.cs b/src/Files.Platform.Linux/Watching/LinuxFolderWatcherFactory.cs index c455a1cf5617..b3c3bc583443 100644 --- a/src/Files.Platform.Linux/Watching/LinuxFolderWatcherFactory.cs +++ b/src/Files.Platform.Linux/Watching/LinuxFolderWatcherFactory.cs @@ -8,6 +8,8 @@ using System.Threading; using System.Threading.Tasks; using Files.Platform.Abstractions.Watching; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; namespace Files.Platform.Linux.Watching { @@ -16,11 +18,18 @@ namespace Files.Platform.Linux.Watching /// public sealed class LinuxFolderWatcherFactory : IFolderWatcherFactory { + private readonly ILogger logger; + + public LinuxFolderWatcherFactory(ILogger? logger = null) + { + this.logger = logger ?? NullLogger.Instance; + } + /// public IFolderWatcher Create(string folderPath, FolderWatcherOptions? options = null) { ArgumentException.ThrowIfNullOrEmpty(folderPath); - return new LinuxFolderWatcher(Path.GetFullPath(folderPath), options ?? new()); + return new LinuxFolderWatcher(Path.GetFullPath(folderPath), options ?? new(), logger); } } } diff --git a/tests/Files.Platform.Tests/Files.Platform.Tests.csproj b/tests/Files.Platform.Tests/Files.Platform.Tests.csproj index edc66578e20d..1d34aec932ba 100644 --- a/tests/Files.Platform.Tests/Files.Platform.Tests.csproj +++ b/tests/Files.Platform.Tests/Files.Platform.Tests.csproj @@ -55,6 +55,12 @@ + + + + + + diff --git a/tests/Files.Platform.Tests/Mime/ApplicationRegistryTests.cs b/tests/Files.Platform.Tests/Mime/ApplicationRegistryTests.cs index b54f21d8dc3c..4fd69a223fad 100644 --- a/tests/Files.Platform.Tests/Mime/ApplicationRegistryTests.cs +++ b/tests/Files.Platform.Tests/Mime/ApplicationRegistryTests.cs @@ -16,6 +16,110 @@ public sealed class ApplicationRegistryTests private static LinuxApplicationRegistry Create(XdgFixture fx, string culture = "en-US", params string[] executables) => new(fx.Directories, CultureInfo.GetCultureInfo(culture), new FakeLocator(executables)); + [TestMethod] + public async Task Cache_ReusesDesktopParsingAndInvalidatesReplacementAndDeletion() + { + using var fx = new XdgFixture(); + fx.WriteDesktop("usr-share", "edit.desktop", "Before", "edit %f"); + var path = Path.Combine(fx.SystemData, "applications", "edit.desktop"); + var registry = Create(fx); + var before = await registry.GetApplicationAsync("edit.desktop"); + Assert.AreSame(before, await registry.GetApplicationAsync("edit.desktop")); + var timestamp = File.GetLastWriteTimeUtc(path); + var replacement = path + ".new"; + File.WriteAllText(replacement, File.ReadAllText(path).Replace("Before", "After!")); + File.SetLastWriteTimeUtc(replacement, timestamp); + File.Move(replacement, path, true); + Assert.AreEqual("After!", (await registry.GetApplicationAsync("edit.desktop"))!.Name); + File.Delete(path); + Assert.IsNull(await registry.GetApplicationAsync("edit.desktop")); + } + + [TestMethod] + public async Task Cache_InvalidatesInPlaceEditsWithRestoredMtime() + { + using var fx = new XdgFixture(); + var desktop = fx.WriteDesktop("usr-share", "a.desktop", "Before", "a %f"); + fx.WriteDesktop("usr-share", "b.desktop", "B", "b %f"); + var associations = fx.Write("config/mimeapps.list", "[Default Applications]\ntext/plain=a.desktop;\n"); + var timestamp = System.DateTime.UtcNow.AddDays(-1); + File.SetLastWriteTimeUtc(desktop, timestamp); + File.SetLastWriteTimeUtc(associations, timestamp); + var registry = Create(fx); + Assert.AreEqual("Before", (await registry.GetDefaultApplicationAsync("text/plain"))!.Name); + await Task.Delay(20); + RewritePreservingMtime(desktop, "Before", "After!"); + Assert.AreEqual("After!", (await registry.GetApplicationAsync("a.desktop"))!.Name); + await Task.Delay(20); + RewritePreservingMtime(associations, "a.desktop", "b.desktop"); + Assert.AreEqual("b.desktop", (await registry.GetDefaultApplicationAsync("text/plain"))!.Id); + } + + private static void RewritePreservingMtime(string path, string before, string after) + { + var timestamp = File.GetLastWriteTimeUtc(path); + var length = new FileInfo(path).Length; + File.WriteAllText(path, File.ReadAllText(path).Replace(before, after)); + File.SetLastWriteTimeUtc(path, timestamp); + Assert.AreEqual(length, new FileInfo(path).Length); + Assert.AreEqual(timestamp, File.GetLastWriteTimeUtc(path)); + } + + [TestMethod] + public async Task Cache_RetriesTransientReadFailureWithoutFileChanges() + { + using var fx = new XdgFixture(); + var path = fx.WriteDesktop("usr-share", "a.desktop", "A", "a %f"); + var registry = Create(fx); + var timestamp = File.GetLastWriteTimeUtc(path); + using (var locked = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None)) + Assert.IsNull(await registry.GetApplicationAsync("a.desktop")); + Assert.AreEqual(timestamp, File.GetLastWriteTimeUtc(path)); + Assert.AreEqual("A", (await registry.GetApplicationAsync("a.desktop"))!.Name); + } + + [TestMethod] + public async Task Cache_InvalidatesMimeInfoAndAssociationsAndUserOverride() + { + using var fx = new XdgFixture(); + fx.WriteDesktop("usr-share", "a.desktop", "A", "a %f"); + fx.WriteDesktop("usr-share", "b.desktop", "B", "b %f"); + fx.Write("usr-share/applications/mimeinfo.cache", "[MIME Cache]\ntext/plain=a.desktop;\n"); + var registry = Create(fx); + Assert.AreEqual("a.desktop", (await registry.GetApplicationsForMimeTypeAsync("text/plain")).Single().Id); + fx.Write("usr-share/applications/mimeinfo.cache", "[MIME Cache]\ntext/plain=b.desktop;a.desktop;\n"); + CollectionAssert.AreEqual(new[] { "b.desktop", "a.desktop" }, (await registry.GetApplicationsForMimeTypeAsync("text/plain")).Select(a => a.Id).ToArray()); + fx.Write("config/mimeapps.list", "[Removed Associations]\ntext/plain=b.desktop;\n"); + Assert.AreEqual("a.desktop", (await registry.GetApplicationsForMimeTypeAsync("text/plain")).Single().Id); + await registry.SetDefaultApplicationAsync("text/plain", "b.desktop"); + Assert.AreEqual("b.desktop", (await registry.GetDefaultApplicationAsync("text/plain"))!.Id); + fx.WriteDesktop("data", "b.desktop", "User B", "b %f"); + Assert.AreEqual("User B", (await registry.GetDefaultApplicationAsync("text/plain"))!.Name); + } + + [TestMethod] + public async Task Cache_FallbackScanSeesNewAndChangedNestedEntries() + { + using var fx = new XdgFixture(); + fx.WriteDesktop("usr-share", "vendor/a.desktop", "A", "a %f", "MimeType=text/plain;\n"); + var registry = Create(fx); + Assert.AreEqual(1, (await registry.GetApplicationsForMimeTypeAsync("text/plain")).Count); + fx.WriteDesktop("usr-share", "vendor/b.desktop", "B", "b %f", "MimeType=text/plain;\n"); + Assert.AreEqual(2, (await registry.GetApplicationsForMimeTypeAsync("text/plain")).Count); + fx.WriteDesktop("usr-share", "vendor/a.desktop", "A", "a %f", "MimeType=image/png;\n"); + Assert.AreEqual("vendor-b.desktop", (await registry.GetApplicationsForMimeTypeAsync("text/plain")).Single().Id); + } + + [TestMethod] + public async Task Cache_ConcurrentQueriesShareParsedEntry() + { + using var fx = new XdgFixture(); + fx.WriteDesktop("usr-share", "a.desktop", "A", "a %f"); + var registry = Create(fx); + var results = await Task.WhenAll(Enumerable.Range(0, 12).Select(_ => registry.GetApplicationAsync("a.desktop"))); + foreach (var result in results) Assert.AreSame(results[0], result); + } + [TestMethod] public async Task Parse_LocalizedNameAndFlags() { diff --git a/tests/Files.Platform.Tests/Mime/ServiceMenuTests.cs b/tests/Files.Platform.Tests/Mime/ServiceMenuTests.cs index 2bf84423f670..a5489484af0b 100644 --- a/tests/Files.Platform.Tests/Mime/ServiceMenuTests.cs +++ b/tests/Files.Platform.Tests/Mime/ServiceMenuTests.cs @@ -28,6 +28,43 @@ private static string Text(string extra = "", string exec = "tool %F") => private static LinuxServiceMenuService Service(XdgFixture fx) => new(fx.Directories, new LinuxMimeTypeService(fx.Directories, CultureInfo.InvariantCulture), CultureInfo.GetCultureInfo("fr-FR")); + [TestMethod] + public async Task Cache_ReusesParsingButRefiltersAndInvalidatesChanges() + { + using var fx = new XdgFixture(); + fx.Write("usr-share/mime/globs2", "50:image/png:*.png\n50:text/plain:*.txt\n"); + var path = fx.Write("data/kio/servicemenus/a.desktop", Text()); + var service = Service(fx); + var first = (await service.GetActionsAsync(["/a.png"])).Single(); + Assert.AreSame(first, (await service.GetActionsAsync(["/b.png"])).Single()); + Assert.AreEqual(0, (await service.GetActionsAsync(["/b.txt"])).Count); + File.WriteAllText(path, Text().Replace("Name[fr]=Exécuter", "Name[fr]=Updated")); + Assert.AreEqual("Updated", (await service.GetActionsAsync(["/a.png"])).Single().Application.Name); + File.WriteAllText(path, Text("Hidden=true\n")); + Assert.AreEqual(0, (await service.GetActionsAsync(["/a.png"])).Count); + File.Delete(path); + fx.Write("usr-share/kio/servicemenus/a.desktop", Text()); + Assert.AreEqual(1, (await service.GetActionsAsync(["/a.png"])).Count); + } + + [TestMethod] + public async Task Cache_InvalidatesAtomicReplacementAndRejectsSymlinkReplacement() + { + using var fx = new XdgFixture(); + fx.Write("usr-share/mime/globs2", "50:image/png:*.png\n"); + var path = fx.Write("data/kio/servicemenus/a.desktop", Text(exec: "tool %F")); + var service = Service(fx); + await service.GetActionsAsync(["/a.png"]); + var timestamp = File.GetLastWriteTimeUtc(path); + var replacement = fx.Write("home/replacement.desktop", Text(exec: "next %F")); + File.SetLastWriteTimeUtc(replacement, timestamp); + File.Move(replacement, path, true); + Assert.AreEqual("next %F", (await service.GetActionsAsync(["/a.png"])).Single().Application.Exec); + File.Move(path, replacement); + File.CreateSymbolicLink(path, replacement); + Assert.AreEqual(0, (await service.GetActionsAsync(["/a.png"])).Count); + } + [TestMethod] public void Parse_LocalizesActionsAndSubmenu_AndPreservesActionOrder() { diff --git a/tests/Files.Platform.Tests/Tags/FileTagsDatabaseTests.cs b/tests/Files.Platform.Tests/Tags/FileTagsDatabaseTests.cs new file mode 100644 index 000000000000..da541740a8a1 --- /dev/null +++ b/tests/Files.Platform.Tests/Tags/FileTagsDatabaseTests.cs @@ -0,0 +1,100 @@ +// Copyright (c) Files Community +// Licensed under the MIT License. + +using Files.App.Utils.FileTags; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.IO; + +namespace Files.Platform.Tests.Tags +{ + [TestClass] + public sealed class FileTagsDatabaseTests + { + [TestMethod] + public void Save_SkipsEmptyAndEqualTagsAndKeepsInputAndOutputIsolated() + { + var root = Path.Combine(Path.GetTempPath(), "files-tags-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(root); + try + { + var path = Path.Combine(root, "tags.json"); + var db = new FileTagsDatabase(path); + db.SetTags("/file", null, []); + Assert.IsFalse(File.Exists(path)); + var tags = new[] { "a", "b" }; + db.SetTags("/file", null, tags); + tags[0] = "changed"; + var timestamp = DateTime.UtcNow.AddDays(-1); + File.SetLastWriteTimeUtc(path, timestamp); + var savedTimestamp = File.GetLastWriteTimeUtc(path); + db.SetTags("/file", null, ["a", "b"]); + db.Import(db.Export()); + db.UpdateTag("/file", null, "/file"); + Assert.AreEqual(savedTimestamp, File.GetLastWriteTimeUtc(path)); + var read = db.GetTags("/file", null); + read[0] = "mutated"; + CollectionAssert.AreEqual(new[] { "a", "b" }, db.GetTags("/file", null)); + db.SetTags("/file", null, ["b", "a"]); + Assert.AreNotEqual(savedTimestamp, File.GetLastWriteTimeUtc(path)); + db.UpdateTag("/file", null, "/renamed"); + Assert.AreEqual(0, db.GetTags("/file", null).Length); + CollectionAssert.AreEqual(new[] { "b", "a" }, new FileTagsDatabase(path).GetTags("/renamed", null)); + db.SetTags("/renamed", null, []); + Assert.AreEqual(0, new FileTagsDatabase(path).GetAll().Count()); + Assert.AreEqual(0, Directory.GetFiles(root, "*.tmp").Length); + } + finally { Directory.Delete(root, true); } + } + + [TestMethod] + public void Save_RetriesFailedPersistenceEvenWhenTagsAreEqual() + { + var root = Path.Combine(Path.GetTempPath(), "files-tags-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(root); + try + { + var path = Path.Combine(root, "tags.json"); + Directory.CreateDirectory(path); + var db = new FileTagsDatabase(path); + db.SetTags("/file", null, ["a"]); + Directory.Delete(path); + db.SetTags("/file", null, ["a"]); + CollectionAssert.AreEqual(new[] { "a" }, new FileTagsDatabase(path).GetTags("/file", null)); + } + finally { Directory.Delete(root, true); } + } + } +} + +// App-only services are never resolved when the database has an explicit test path. +namespace Files.App.Utils.FileTags +{ + [System.Text.Json.Serialization.JsonSerializable(typeof(TaggedFile[]))] + [System.Text.Json.Serialization.JsonSerializable(typeof(System.Collections.Generic.List))] + internal partial class AppJsonSerializerContext : System.Text.Json.Serialization.JsonSerializerContext { } + + internal sealed class RegistrySerializableAttribute : Attribute { } + + internal sealed class Ioc + { + public static Ioc Default { get; } = new(); + public IServiceProvider? Services { get; set; } + public T? GetService() where T : class => Services?.GetService(typeof(T)) as T; + public T GetRequiredService() => Services?.GetService(typeof(T)) is T service + ? service : throw new InvalidOperationException("Tests must use an explicit database path or register services."); + } + + internal static class App + { + public static Microsoft.Extensions.Logging.ILogger? Logger => null; + } + + internal static class SafetyExtensions + { + public static void IgnoreExceptions(Action action) + { + try { action(); } catch (IOException) { } + } + } +} diff --git a/tests/Files.Platform.Tests/Tags/FileTagsHelperTests.cs b/tests/Files.Platform.Tests/Tags/FileTagsHelperTests.cs new file mode 100644 index 000000000000..9ee0854ecb28 --- /dev/null +++ b/tests/Files.Platform.Tests/Tags/FileTagsHelperTests.cs @@ -0,0 +1,182 @@ +// Copyright (c) Files Community +// Licensed under the MIT License. + +using Files.App.Utils.FileTags; +using Files.Platform.Abstractions.Tags; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.IO; +using System.Threading; +using System.Threading.Tasks; + +namespace Files.Platform.Tests.Tags +{ + [TestClass] + [DoNotParallelize] + public sealed class FileTagsHelperTests + { + [TestMethod] + public async Task Drain_WaitsForAllQueuedEditsAndPersistsThem() + { + using var fixture = new TagFixture(); + _ = FileTagsHelper.WriteFileTagAsync("/blocked", ["a"]); + await fixture.Store.Entered.Task.WaitAsync(TimeSpan.FromSeconds(10)); + for (var i = 0; i < 12; i++) + _ = FileTagsHelper.WriteFileTagAsync("/file" + i, ["b"]); + var drain = FileTagsHelper.DrainPendingWritesAsync(); + Assert.IsFalse(drain.IsCompleted); + fixture.Store.Release.Set(); + await drain.WaitAsync(TimeSpan.FromSeconds(10)); + var reloaded = new FileTagsDatabase(fixture.DatabasePath); + CollectionAssert.AreEqual(new[] { "a" }, reloaded.GetTags("/blocked", null)); + for (var i = 0; i < 12; i++) + { + CollectionAssert.AreEqual(new[] { "b" }, reloaded.GetTags("/file" + i, null)); + CollectionAssert.AreEqual(new[] { "B" }, fixture.Store.Tags["/file" + i]); + } + } + + [TestMethod] + public async Task BulkDeletion_PreservesQueuedAdditionsAndIncludesNewlyTaggedFiles() + { + using var fixture = new TagFixture(); + FileTagsHelper.GetDbInstance().SetTags("/existing", null, ["a"]); + _ = FileTagsHelper.WriteFileTagAsync("/blocked", ["a"]); + await fixture.Store.Entered.Task.WaitAsync(TimeSpan.FromSeconds(10)); + _ = FileTagsHelper.WriteFileTagAsync("/existing", ["a", "b"]); + _ = FileTagsHelper.WriteFileTagAsync("/new", ["a", "b"]); + fixture.Settings.FileTagList = [new("b", "B")]; + var deletion = FileTagsHelper.UntagAllFilesAsync("a"); + Assert.IsFalse(deletion.IsCompleted); + fixture.Store.Release.Set(); + Assert.IsTrue(await deletion.WaitAsync(TimeSpan.FromSeconds(10))); + await FileTagsHelper.DrainPendingWritesAsync(); + var reloaded = new FileTagsDatabase(fixture.DatabasePath); + foreach (var path in new[] { "/existing", "/new" }) + { + CollectionAssert.AreEqual(new[] { "b" }, reloaded.GetTags(path, null)); + CollectionAssert.AreEqual(new[] { "B" }, fixture.Store.Tags[path]); + } + Assert.AreEqual(0, reloaded.GetTags("/blocked", null).Length); + Assert.AreEqual(0, fixture.Store.Tags["/blocked"].Length); + } + + [TestMethod] + [DataRow(true)] + [DataRow(false)] + public async Task BulkDeletion_SerializesPropertyLoadingReadAndDatabaseUpdate(bool supportsXattrs) + { + using var fixture = new TagFixture(); + fixture.Store.SupportsXattrs = supportsXattrs; + fixture.Store.BlockReads = true; + fixture.Store.Tags["/existing"] = ["A", "B"]; + if (!supportsXattrs) + FileTagsHelper.GetDbInstance().SetTags("/existing", null, ["a", "b"]); + + var loading = FileTagsHelper.ReadAndUpdateFileTagsAsync("/existing"); + await fixture.Store.ReadEntered.Task.WaitAsync(TimeSpan.FromSeconds(10)); + var deletion = FileTagsHelper.UntagAllFilesAsync("a"); + var reloading = FileTagsHelper.ReadAndUpdateFileTagsAsync("/existing"); + Assert.IsFalse(deletion.IsCompleted); + Assert.IsFalse(reloading.IsCompleted); + fixture.Store.ReadRelease.Set(); + CollectionAssert.AreEqual(new[] { "a", "b" }, await loading.WaitAsync(TimeSpan.FromSeconds(10))); + Assert.IsTrue(await deletion.WaitAsync(TimeSpan.FromSeconds(10))); + + CollectionAssert.AreEqual(new[] { "b" }, await reloading.WaitAsync(TimeSpan.FromSeconds(10))); + var reloaded = new FileTagsDatabase(fixture.DatabasePath); + CollectionAssert.AreEqual(new[] { "b" }, reloaded.GetTags("/existing", null)); + } + + private sealed class TagFixture : IDisposable + { + private readonly string root = Path.Combine(Path.GetTempPath(), "files-tags-queue-" + Guid.NewGuid().ToString("N")); + private readonly ServiceProvider services; + public string DatabasePath => Path.Combine(root, "tags.json"); + public BlockingTagStore Store { get; } = new(); + public TagSettings Settings { get; } = new(); + + public TagFixture() + { + Directory.CreateDirectory(root); + FileTagsHelper.Database = new FileTagsDatabase(DatabasePath); + services = new ServiceCollection().AddSingleton(Store) + .AddSingleton(Settings).BuildServiceProvider(); + Ioc.Default.Services = services; + } + + public void Dispose() + { + Store.Release.Set(); + Store.ReadRelease.Set(); + FileTagsHelper.DrainPendingWritesAsync().GetAwaiter().GetResult(); + Ioc.Default.Services = null; + services.Dispose(); + Store.Release.Dispose(); + Store.ReadRelease.Dispose(); + Directory.Delete(root, true); + } + } + + private sealed class BlockingTagStore : IFileTagsStore + { + public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public ManualResetEventSlim Release { get; } = new(); + public Dictionary Tags { get; } = new(); + public bool SupportsXattrs { get; set; } = true; + public bool BlockReads { get; set; } + public TaskCompletionSource ReadEntered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public ManualResetEventSlim ReadRelease { get; } = new(); + public IReadOnlyList ReadTags(string path) + { + if (BlockReads && !ReadEntered.Task.IsCompleted) + { + ReadEntered.SetResult(); + if (!ReadRelease.Wait(TimeSpan.FromSeconds(10))) throw new TimeoutException(); + } + return SupportsXattrs ? Tags.GetValueOrDefault(path) ?? [] : []; + } + public bool WriteTags(string path, IReadOnlyList tags) + { + if (path == "/blocked" && !Entered.Task.IsCompleted) + { + Entered.SetResult(); + if (!Release.Wait(TimeSpan.FromSeconds(10))) throw new TimeoutException(); + } + if (!SupportsXattrs) return false; + Tags[path] = tags.ToArray(); + return true; + } + } + + private sealed class TagSettings : IFileTagsSettingsService + { + public IList FileTagList { get; set; } = [new("a", "A"), new("b", "B")]; + public IList? GetTagsByIds(string[] tags) => FileTagList.Where(tag => tags.Contains(tag.Uid)).ToList(); + public IEnumerable GetTagsByName(string name) => FileTagList.Where(tag => tag.Name == name); + } + } +} + +namespace Files.App.Utils.FileTags +{ + public static partial class FileTagsHelper + { + internal static FileTagsDatabase Database { get; set; } = null!; + public static FileTagsDatabase GetDbInstance() => Database; + } + + internal sealed record TestTag(string Uid, string Name); + + internal interface IFileTagsSettingsService + { + IList FileTagList { get; } + IList? GetTagsByIds(string[] tags); + IEnumerable GetTagsByName(string name); + } + + internal static class LogPathHelper + { + public static string RedactPath(string path) => path; + } +} diff --git a/tests/Files.Platform.Tests/Watching/LinuxFolderWatcherTests.cs b/tests/Files.Platform.Tests/Watching/LinuxFolderWatcherTests.cs index 07d109217d55..bc506f4f0a9a 100644 --- a/tests/Files.Platform.Tests/Watching/LinuxFolderWatcherTests.cs +++ b/tests/Files.Platform.Tests/Watching/LinuxFolderWatcherTests.cs @@ -10,6 +10,7 @@ using Files.Platform.Abstractions.Watching; using Files.Platform.Linux.Watching; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Concurrent; @@ -59,6 +60,30 @@ public async Task WaitForAsync(string ev) } } + private sealed class PollingLogger : ILogger + { + public List Messages { get; } = []; + public IDisposable? BeginScope(TState state) where TState : notnull => null; + public bool IsEnabled(LogLevel level) => true; + public void Log(LogLevel level, EventId id, TState state, Exception? exception, Func formatter) + => Messages.Add(formatter(state, exception)); + } + + [TestMethod] + public void Polling_LogsOnceAcrossRestartsWithoutExposingFolderPath() + { + var logger = new PollingLogger(); + using var watcher = new LinuxFolderWatcherFactory(logger).Create(_root, new FolderWatcherOptions { ForcePolling = true }); + watcher.Start(); + Assert.IsTrue(watcher.IsPolling); + watcher.Stop(); + watcher.Start(); + Assert.AreEqual(1, logger.Messages.Count); + StringAssert.Contains(logger.Messages[0], "fallback polling"); + StringAssert.Contains(logger.Messages[0], "2000"); + Assert.IsFalse(logger.Messages[0].Contains(_root, StringComparison.Ordinal)); + } + [TestMethod] public void AddLinuxWatching_RegistersFactory() {