From d3009fbb67f76337949faa99cd7180d23451f8ca Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 24 Sep 2022 12:41:17 -0500 Subject: add sync/async overloads for filling, make scans cancellable --- src/slskd/Shares/ISharedFileCache.cs | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) (limited to 'src/slskd/Shares/ISharedFileCache.cs') diff --git a/src/slskd/Shares/ISharedFileCache.cs b/src/slskd/Shares/ISharedFileCache.cs index 52c7783c..af151353 100644 --- a/src/slskd/Shares/ISharedFileCache.cs +++ b/src/slskd/Shares/ISharedFileCache.cs @@ -19,7 +19,6 @@ namespace slskd.Shares { using System.Collections.Generic; using System.Text.RegularExpressions; - using System.Threading; using System.Threading.Tasks; using Soulseek; @@ -42,12 +41,10 @@ namespace slskd.Shares /// /// Scans the configured shares and fills the cache. /// - /// Initiates the scan, then yields execution back to the caller; does not wait for the operation to complete. /// The list of shares from which to fill the cache. /// The list of regular expressions used to exclude files or paths from scanning. - /// The optional cancellation token to monitor. /// The operation context. - Task FillAsync(IEnumerable shares, IEnumerable filters, CancellationToken cancellationToken = default); + Task FillAsync(IEnumerable shares, IEnumerable filters); /// /// Returns the contents of the specified . @@ -62,7 +59,7 @@ namespace slskd.Shares /// /// The fully qualified filename to unmask. /// The unmasked filename. - public string Resolve(string filename); + string Resolve(string filename); /// /// Searches the cache for the specified and returns the matching files. @@ -71,10 +68,24 @@ namespace slskd.Shares /// The matching files. IEnumerable Search(SearchQuery query); + /// + /// Starts a scan of the configured shares and fills the cache. + /// + /// The list of shares from which to fill the cache. + /// The list of regular expressions used to exclude files or paths from scanning. + /// The operation context. + Task StartFillAsync(IEnumerable shares, IEnumerable filters); + + /// + /// Cancels the currently running fill operation, if one is running. + /// + /// A value indicating whether a fill operation was cancelled. + bool TryCancelFill(); + /// /// Attempts to load the cache from disk. /// /// A value indicating whether the load was successful. bool TryLoad(); } -} +} \ No newline at end of file -- cgit v1.2.3 From 6484666fc88126f3216846409e3f1b81b2a78677 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 24 Sep 2022 16:23:04 -0500 Subject: undo separation of start/scan, improve cancellation logic --- src/slskd/Shares/IShareService.cs | 7 ---- src/slskd/Shares/ISharedFileCache.cs | 8 ----- src/slskd/Shares/ShareService.cs | 13 ++----- src/slskd/Shares/SharedFileCache.cs | 70 +++++++++++++++--------------------- 4 files changed, 31 insertions(+), 67 deletions(-) (limited to 'src/slskd/Shares/ISharedFileCache.cs') diff --git a/src/slskd/Shares/IShareService.cs b/src/slskd/Shares/IShareService.cs index 12603283..b625286e 100644 --- a/src/slskd/Shares/IShareService.cs +++ b/src/slskd/Shares/IShareService.cs @@ -76,13 +76,6 @@ namespace slskd.Shares /// Thrown when a scan is already in progress. Task ScanAsync(); - /// - /// Starts a scan of the configured shares. - /// - /// The operation context. - /// Thrown when a scan is already in progress. - Task StartScanAsync(); - /// /// Cancels the currently running scan, if one is running. /// diff --git a/src/slskd/Shares/ISharedFileCache.cs b/src/slskd/Shares/ISharedFileCache.cs index af151353..73c9cd56 100644 --- a/src/slskd/Shares/ISharedFileCache.cs +++ b/src/slskd/Shares/ISharedFileCache.cs @@ -68,14 +68,6 @@ namespace slskd.Shares /// The matching files. IEnumerable Search(SearchQuery query); - /// - /// Starts a scan of the configured shares and fills the cache. - /// - /// The list of shares from which to fill the cache. - /// The list of regular expressions used to exclude files or paths from scanning. - /// The operation context. - Task StartFillAsync(IEnumerable shares, IEnumerable filters); - /// /// Cancels the currently running fill operation, if one is running. /// diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index 72a0fea6..17817b86 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -52,9 +52,10 @@ namespace slskd.Shares State.SetValue(state => state with { // scan is pending if faulted, or if state DIDN'T just transition from filling to not filling AND a scan was already pending - ScanPending = current.Faulted || (!(previous.Filling && !current.Filling) && state.ScanPending), + ScanPending = current.Faulted || current.Cancelled || (!(previous.Filling && !current.Filling) && state.ScanPending), Scanning = current.Filling, Faulted = current.Faulted, + Cancelled = current.Cancelled, Ready = current.Filled, ScanProgress = current.FillProgress, Directories = current.Directories, @@ -168,16 +169,6 @@ namespace slskd.Shares return Cache.FillAsync(Shares, FilterRegexes); } - /// - /// Starts a scan of the configured shares. - /// - /// The operation context. - /// Thrown when a scan is already in progress. - public Task StartScanAsync() - { - return Cache.StartFillAsync(Shares, FilterRegexes); - } - /// /// Cancels the currently running scan, if one is running. /// diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index dd399e68..17fc5fb5 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -126,29 +126,13 @@ namespace slskd.Shares return directories.Values.OrderBy(d => d.Name); } - /// - /// Starts a scan of the configured shares and fills the cache. - /// - /// The list of shares from which to fill the cache. - /// The list of regular expressions used to exclude files or paths from scanning. - /// The operation context. - public Task StartFillAsync(IEnumerable shares, IEnumerable filters) - { - return FillInternalAsync(shares, filters, continueAsync: true); - } - /// /// Scans the configured shares and fills the cache. /// /// The list of shares from which to fill the cache. /// The list of regular expressions used to exclude files or paths from scanning. /// The operation context. - public Task FillAsync(IEnumerable shares, IEnumerable filters) - { - return FillInternalAsync(shares, filters, continueAsync: false); - } - - private async Task FillInternalAsync(IEnumerable shares, IEnumerable filters, bool continueAsync = true) + public async Task FillAsync(IEnumerable shares, IEnumerable filters) { // obtain the semaphore, or fail if it can't be obtained immediately, indicating that a scan is running. if (!await SyncRoot.WaitAsync(millisecondsTimeout: 0)) @@ -160,12 +144,17 @@ namespace slskd.Shares CancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(Program.MasterCancellationTokenSource.Token); var cancellationToken = CancellationTokenSource.Token; + // send control back to the calling context. if we don't do this, the caller will block until + // directories have been enumerated. + await Task.Yield(); + try { State.SetValue(state => state with { Filling = true, Filled = false, + Cancelled = false, FillProgress = 0, Directories = 0, Files = 0, @@ -183,11 +172,6 @@ namespace slskd.Shares Log.Debug("Starting shared file scan"); - if (continueAsync) - { - await Task.Yield(); - } - var timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); var sw = new Stopwatch(); @@ -320,16 +304,7 @@ namespace slskd.Shares cached += addedFiles; Log.Debug("Finished scanning {Directory}: {Added} files added and {Filtered} filtered", directory, addedFiles, filteredFiles); - - try - { - State.SetValue(state => state with { FillProgress = current / (double)unmaskedDirectories.Count, Files = cached }); - } - catch (Exception ex) - { - Log.Error(ex, "Failed to set cache state following scan of {Directory}: {Message}", directory, ex.Message); - throw; - } + State.SetValue(state => state with { FillProgress = current / (double)unmaskedDirectories.Count, Files = cached }); })); } @@ -337,17 +312,28 @@ namespace slskd.Shares workers.ForEach(w => w.Start()); Log.Debug("All workers started"); - Log.Debug("Filling DirectoryChannel..."); - foreach (var directory in unmaskedDirectories) + try { - await channel.Writer.WriteAsync(directory, cancellationToken); - } + try + { + Log.Debug("Filling DirectoryChannel..."); + foreach (var directory in unmaskedDirectories) + { + await channel.Writer.WriteAsync(directory, cancellationToken); + } - channel.Writer.Complete(); - Log.Debug("DirectoryChannel filled"); + Log.Debug("DirectoryChannel filled"); + } + catch (OperationCanceledException) + { + Log.Warning("Shared file scan cancellation requested"); + Log.Debug("DirectoryChannel fill aborted"); + } + finally + { + channel.Writer.Complete(); + } - try - { Log.Debug("Waiting for workers to finish working..."); await Task.WhenAll(workers.Select(w => w.Completed)); Log.Debug("All workers finished"); @@ -363,7 +349,9 @@ namespace slskd.Shares catch (OperationCanceledException) { // important! don't try to delete stale files in this case; unscanned records will have a stale timestamp - Log.Warning("Shared file scan cancelled by user"); + Log.Warning("Shared file scan cancelled successfully"); + + State.SetValue(state => state with { Cancelled = true }); } Log.Debug("Backing up shared file cache database..."); -- cgit v1.2.3 From 9b8d59a93b4661f7e3650e025b725498b9a5567b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 24 Sep 2022 17:19:20 -0500 Subject: improve shares UI performance --- .../Shares/API/Controllers/SharesController.cs | 38 ++---- src/slskd/Shares/IShareService.cs | 9 +- src/slskd/Shares/ISharedFileCache.cs | 17 ++- src/slskd/Shares/ShareService.cs | 16 ++- src/slskd/Shares/SharedFileCache.cs | 152 +++++++++++++++------ 5 files changed, 162 insertions(+), 70 deletions(-) (limited to 'src/slskd/Shares/ISharedFileCache.cs') diff --git a/src/slskd/Shares/API/Controllers/SharesController.cs b/src/slskd/Shares/API/Controllers/SharesController.cs index 44d79a18..5f87f900 100644 --- a/src/slskd/Shares/API/Controllers/SharesController.cs +++ b/src/slskd/Shares/API/Controllers/SharesController.cs @@ -57,18 +57,13 @@ namespace slskd.Shares.API [ProducesResponseType(typeof(IEnumerable), 200)] public async Task List() { - var browse = await Shares.BrowseAsync(); + var shares = new List(); - var summary = Shares.Shares.Select(share => + foreach (var share in Shares.Shares) { - var directories = browse.Where(directory => directory.Name.StartsWith(share.RemotePath)); - var fileCount = directories.Aggregate(seed: 0, (sum, directory) => - { - sum += directory.FileCount; - return sum; - }); + var (directories, files) = await Shares.SummarizeShareAsync(share); - return new SummarizedShare() + shares.Add(new SummarizedShare() { Id = share.Id, Alias = share.Alias, @@ -76,12 +71,12 @@ namespace slskd.Shares.API LocalPath = share.LocalPath, Raw = share.Raw, RemotePath = share.RemotePath, - Directories = directories.Count(), - Files = fileCount, - }; - }); + Directories = directories, + Files = files, + }); + } - return Ok(summary); + return Ok(shares); } /// @@ -104,13 +99,7 @@ namespace slskd.Shares.API return NotFound(); } - var browse = await Shares.BrowseAsync(); - var directories = browse.Where(directory => directory.Name.StartsWith(share.RemotePath)); - var fileCount = directories.Aggregate(seed: 0, (sum, directory) => - { - sum += directory.FileCount; - return sum; - }); + var (directories, files) = await Shares.SummarizeShareAsync(share); var summary = new SummarizedShare() { @@ -120,8 +109,8 @@ namespace slskd.Shares.API LocalPath = share.LocalPath, Raw = share.Raw, RemotePath = share.RemotePath, - Directories = directories.Count(), - Files = fileCount, + Directories = directories, + Files = files, }; return Ok(summary); @@ -159,8 +148,7 @@ namespace slskd.Shares.API return NotFound(); } - var contents = (await Shares.BrowseAsync()) - .Where(directory => directory.Name.StartsWith(share.RemotePath)); + var contents = await Shares.BrowseAsync(share); return Ok(contents); } diff --git a/src/slskd/Shares/IShareService.cs b/src/slskd/Shares/IShareService.cs index b625286e..73f6a4ad 100644 --- a/src/slskd/Shares/IShareService.cs +++ b/src/slskd/Shares/IShareService.cs @@ -42,7 +42,7 @@ namespace slskd.Shares /// Returns the entire contents of the share. /// /// The entire contents of the share. - Task> BrowseAsync(); + Task> BrowseAsync(Share share = null); /// /// Returns the contents of the specified . @@ -76,6 +76,13 @@ namespace slskd.Shares /// Thrown when a scan is already in progress. Task ScanAsync(); + /// + /// Gets summary information for the specified . + /// + /// The share to summarize. + /// The summary information. + Task<(int Directories, int Files)> SummarizeShareAsync(Share share); + /// /// Cancels the currently running scan, if one is running. /// diff --git a/src/slskd/Shares/ISharedFileCache.cs b/src/slskd/Shares/ISharedFileCache.cs index 73c9cd56..c59f5bba 100644 --- a/src/slskd/Shares/ISharedFileCache.cs +++ b/src/slskd/Shares/ISharedFileCache.cs @@ -35,8 +35,23 @@ namespace slskd.Shares /// /// Returns the contents of the cache. /// + /// The optional share to which to limit the scope of the browse. /// The contents of the cache. - IEnumerable Browse(); + IEnumerable Browse(Share share = null); + + /// + /// Returns the number of directories in the specified . + /// + /// The share for which the directories are to be counted. + /// The number of directories. + int CountDirectories(Share share); + + /// + /// Returns the number of files in the specified . + /// + /// The share for which the files are to be counted. + /// The number of files. + int CountFiles(Share share); /// /// Scans the configured shares and fills the cache. diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index 17817b86..4307a98f 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -91,9 +91,9 @@ namespace slskd.Shares /// Returns the entire contents of the share. /// /// The entire contents of the share. - public Task> BrowseAsync() + public Task> BrowseAsync(Share share = null) { - var results = Cache.Browse(); + var results = Cache.Browse(share); var normalizedResults = results.Select(r => new Directory(r.Name.NormalizePath(), r.Files)); return Task.FromResult(normalizedResults); @@ -169,6 +169,18 @@ namespace slskd.Shares return Cache.FillAsync(Shares, FilterRegexes); } + /// + /// Gets summary information for the specified . + /// + /// The share to summarize. + /// The summary information. + public Task<(int Directories, int Files)> SummarizeShareAsync(Share share) + { + var dirs = Cache.CountDirectories(share); + var files = Cache.CountFiles(share); + return Task.FromResult((dirs, files)); + } + /// /// Cancels the currently running scan, if one is running. /// diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index 17fc5fb5..a10202e2 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -25,6 +25,7 @@ namespace slskd.Shares using System.Data; using System.Diagnostics; using System.Linq; + using System.Security.Cryptography; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Channels; @@ -68,41 +69,30 @@ namespace slskd.Shares /// /// Returns the contents of the cache. /// + /// The optional share to which to limit the scope of the browse. /// The contents of the cache. - public IEnumerable Browse() + public IEnumerable Browse(Share share = null) { var directories = new ConcurrentDictionary(); + string prefix = null; + + if (share != null) + { + prefix = share.RemotePath + Path.DirectorySeparatorChar; + } + // Soulseek requires that each directory in the tree have an entry in the list returned in a browse response. if // missing, files that are nested within directories which contain only directories (no files) are displayed as being // in the root. to get around this, prime a dictionary with all known directories, and an empty Soulseek.Directory. if // there are any files in the directory, this entry will be overwritten with a new Soulseek.Directory containing the // files. if not they'll be left as is. - foreach (var directory in ListDirectories()) + foreach (var directory in ListDirectories(prefix)) { directories.TryAdd(directory, new Directory(directory)); } - var files = new List(); - - using var conn = GetConnection(); - using var cmd = new SqliteCommand("SELECT maskedFilename, code, size, extension, attributeJson FROM files ORDER BY maskedFilename ASC;", conn); - var reader = cmd.ExecuteReader(); - - while (reader.Read()) - { - var filename = reader.GetString(0); - var code = reader.GetInt32(1); - var size = reader.GetInt64(2); - var extension = reader.GetString(3); - var attributeJson = reader.GetString(4); - - var attributeList = attributeJson.FromJson>(); - - var file = new File(code, filename, size, extension, attributeList); - - files.Add(file); - } + var files = ListFiles(prefix, includeFullPath: true); var groups = files .GroupBy(file => Path.GetDirectoryName(file.Filename)) @@ -126,6 +116,28 @@ namespace slskd.Shares return directories.Values.OrderBy(d => d.Name); } + /// + /// Returns the number of directories in the specified . + /// + /// The share for which the directories are to be counted. + /// The number of directories. + public int CountDirectories(Share share) + { + var path = share.RemotePath + Path.DirectorySeparatorChar; + return CountDirectories(path); + } + + /// + /// Returns the number of files in the specified . + /// + /// The share for which the files are to be counted. + /// The number of files. + public int CountFiles(Share share) + { + var path = share.RemotePath + Path.DirectorySeparatorChar; + return CountFiles(path); + } + /// /// Scans the configured shares and fills the cache. /// @@ -623,22 +635,60 @@ namespace slskd.Shares sourceConn.BackupDatabase(backupConn); } - private int CountDirectories() + private int CountDirectories(string prefix = null) { using var conn = GetConnection(); - using var cmd = new SqliteCommand("SELECT COUNT(*) FROM directories;", conn); - var reader = cmd.ExecuteReader(); - reader.Read(); - return reader.GetInt32(0); + + SqliteCommand cmd = default; + + try + { + if (string.IsNullOrEmpty(prefix)) + { + cmd = new SqliteCommand("SELECT COUNT(*) FROM directories;", conn); + } + else + { + cmd = new SqliteCommand("SELECT COUNT(*) FROM directories WHERE name LIKE @prefix || '%'", conn); + cmd.Parameters.AddWithValue("prefix", prefix); + } + + var reader = cmd.ExecuteReader(); + reader.Read(); + return reader.GetInt32(0); + } + finally + { + cmd.Dispose(); + } } - private int CountFiles() + private int CountFiles(string prefix = null) { using var conn = GetConnection(); - using var cmd = new SqliteCommand("SELECT COUNT(*) FROM files;", conn); - var reader = cmd.ExecuteReader(); - reader.Read(); - return reader.GetInt32(0); + + SqliteCommand cmd = default; + + try + { + if (string.IsNullOrEmpty(prefix)) + { + cmd = new SqliteCommand("SELECT COUNT(*) FROM files;", conn); + } + else + { + cmd = new SqliteCommand("SELECT COUNT(*) FROM files WHERE maskedFilename LIKE @prefix || '%'", conn); + cmd.Parameters.AddWithValue("prefix", prefix); + } + + var reader = cmd.ExecuteReader(); + reader.Read(); + return reader.GetInt32(0); + } + finally + { + cmd.Dispose(); + } } private SqliteConnection GetConnection(string connectionString = null) @@ -710,24 +760,42 @@ namespace slskd.Shares return reader.GetInt64(0); } - private IEnumerable ListDirectories() + private IEnumerable ListDirectories(string prefix = null) { var results = new List(); using var conn = GetConnection(); - using var cmd = new SqliteCommand("SELECT name FROM directories ORDER BY name ASC;", conn); - var reader = cmd.ExecuteReader(); + SqliteCommand cmd = default; - while (reader.Read()) + try { - results.Add(reader.GetString(0)); - } + if (string.IsNullOrEmpty(prefix)) + { + cmd = new SqliteCommand("SELECT name FROM directories ORDER BY name ASC;", conn); + } + else + { + cmd = new SqliteCommand("SELECT name from directories WHERE name LIKE @prefix || '%' ORDER BY name ASC;", conn); + cmd.Parameters.AddWithValue("prefix", prefix); + } + + var reader = cmd.ExecuteReader(); + + while (reader.Read()) + { + results.Add(reader.GetString(0)); + } - return results; + return results; + } + finally + { + cmd.Dispose(); + } } - private IEnumerable ListFiles(string directory = null) + private IEnumerable ListFiles(string directory = null, bool includeFullPath = false) { var results = new List(); @@ -758,7 +826,9 @@ namespace slskd.Shares var attributeList = attributeJson.FromJson>(); - var file = new File(code, filename: Path.GetFileName(filename), size, extension, attributeList); + filename = includeFullPath ? filename : Path.GetFileName(filename); + + var file = new File(code, filename, size, extension, attributeList); results.Add(file); } -- cgit v1.2.3