aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2022-11-04 10:51:17 -0500
committerGitHub <noreply@github.com>2022-11-04 10:51:17 -0500
commite31e9e5b0967d777fccb76a4c6113052a05b49fd (patch)
tree13408700fcbdc7ac681a6c51b7d4f2aac34cf5b5 /src
parent3b75717ab4562a516769bc731ac978db59297a08 (diff)
parent964d50bc5156069b4404f29f823a4a21bd15ffe5 (diff)
downloadslskd-e31e9e5b0967d777fccb76a4c6113052a05b49fd.tar.gz
Merge pull request #730 from slskd/shares
Improve computation of share statistics, fix a few bugs with network functionality
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Shares/API/Controllers/SharesController.cs45
-rw-r--r--src/slskd/Shares/API/DTO/SummarizedShare.cs31
-rw-r--r--src/slskd/Shares/IShareService.cs14
-rw-r--r--src/slskd/Shares/ShareScanner.cs34
-rw-r--r--src/slskd/Shares/ShareService.cs68
-rw-r--r--src/slskd/Shares/Types/Share.cs14
-rw-r--r--src/web/src/components/System/Shares/ShareTable.js2
-rw-r--r--src/web/src/components/System/Shares/index.js8
8 files changed, 101 insertions, 115 deletions
diff --git a/src/slskd/Shares/API/Controllers/SharesController.cs b/src/slskd/Shares/API/Controllers/SharesController.cs
index 671e8992..e4f82848 100644
--- a/src/slskd/Shares/API/Controllers/SharesController.cs
+++ b/src/slskd/Shares/API/Controllers/SharesController.cs
@@ -53,29 +53,14 @@ namespace slskd.Shares.API
/// <returns></returns>
[HttpGet("")]
[Authorize(Policy = AuthPolicy.Any)]
- [ProducesResponseType(typeof(IEnumerable<SummarizedShare>), 200)]
- public async Task<IActionResult> List()
+ [ProducesResponseType(typeof(Dictionary<string, IEnumerable<Share>>), 200)]
+ public IActionResult List()
{
- var shares = new List<SummarizedShare>();
+ var response = Shares.Hosts.ToDictionary(
+ keySelector: host => host.Name,
+ elementSelector: host => host.Shares);
- foreach (var share in Shares.Hosts.SelectMany(host => host.Shares))
- {
- var (directories, files) = await Shares.SummarizeShareAsync(share);
-
- shares.Add(new SummarizedShare()
- {
- Id = share.Id,
- Alias = share.Alias,
- IsExcluded = share.IsExcluded,
- LocalPath = share.LocalPath,
- Raw = share.Raw,
- RemotePath = share.RemotePath,
- Directories = directories,
- Files = files,
- });
- }
-
- return Ok(shares);
+ return Ok(response);
}
/// <summary>
@@ -87,7 +72,7 @@ namespace slskd.Shares.API
/// <returns></returns>
[HttpGet("{id}")]
[Authorize(Policy = AuthPolicy.Any)]
- [ProducesResponseType(typeof(SummarizedShare), 200)]
+ [ProducesResponseType(typeof(Share), 200)]
[ProducesResponseType(404)]
public async Task<IActionResult> Get(string id)
{
@@ -98,21 +83,7 @@ namespace slskd.Shares.API
return NotFound();
}
- var (directories, files) = await Shares.SummarizeShareAsync(share);
-
- var summary = new SummarizedShare()
- {
- Id = share.Id,
- Alias = share.Alias,
- IsExcluded = share.IsExcluded,
- LocalPath = share.LocalPath,
- Raw = share.Raw,
- RemotePath = share.RemotePath,
- Directories = directories,
- Files = files,
- };
-
- return Ok(summary);
+ return Ok(share);
}
/// <summary>
diff --git a/src/slskd/Shares/API/DTO/SummarizedShare.cs b/src/slskd/Shares/API/DTO/SummarizedShare.cs
deleted file mode 100644
index 4e296d1c..00000000
--- a/src/slskd/Shares/API/DTO/SummarizedShare.cs
+++ /dev/null
@@ -1,31 +0,0 @@
-// <copyright file="SummarizedShare.cs" company="slskd Team">
-// Copyright (c) slskd Team. All rights reserved.
-//
-// This program is free software: you can redistribute it and/or modify
-// it under the terms of the GNU Affero General Public License as published
-// by the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU Affero General Public License for more details.
-//
-// You should have received a copy of the GNU Affero General Public License
-// along with this program. If not, see https://www.gnu.org/licenses/.
-// </copyright>
-
-namespace slskd.Shares
-{
- public record SummarizedShare
- {
- public string Id { get; init; }
- public string Alias { get; init; }
- public bool IsExcluded { get; init; }
- public string LocalPath { get; init; }
- public string Raw { get; init; }
- public string RemotePath { get; init; }
- public int Directories { get; init; }
- public int Files { get; init; }
- }
-} \ No newline at end of file
diff --git a/src/slskd/Shares/IShareService.cs b/src/slskd/Shares/IShareService.cs
index 34f1bde8..dff6a8ce 100644
--- a/src/slskd/Shares/IShareService.cs
+++ b/src/slskd/Shares/IShareService.cs
@@ -54,6 +54,13 @@ namespace slskd.Shares
Task<IEnumerable<Directory>> BrowseAsync(Share share = null);
/// <summary>
+ /// Gets statistical information for the specified <paramref name="share"/>.
+ /// </summary>
+ /// <param name="share">The share to summarize.</param>
+ /// <returns>The summary information.</returns>
+ Task<(int Directories, int Files)> ComputeShareStatisticsAsync(Share share);
+
+ /// <summary>
/// Dumps the local share cache to a file.
/// </summary>
/// <param name="filename">The destination file.</param>
@@ -113,13 +120,6 @@ namespace slskd.Shares
Task ScanAsync();
/// <summary>
- /// Gets summary information for the specified <paramref name="share"/>.
- /// </summary>
- /// <param name="share">The share to summarize.</param>
- /// <returns>The summary information.</returns>
- Task<(int Directories, int Files)> SummarizeShareAsync(Share share);
-
- /// <summary>
/// Cancels the currently running scan on the local host, if one is running.
/// </summary>
/// <returns>A value indicating whether a scan was cancelled.</returns>
diff --git a/src/slskd/Shares/ShareScanner.cs b/src/slskd/Shares/ShareScanner.cs
index d2002e19..1648c850 100644
--- a/src/slskd/Shares/ShareScanner.cs
+++ b/src/slskd/Shares/ShareScanner.cs
@@ -45,8 +45,9 @@ namespace slskd.Shares
/// </summary>
/// <param name="shares">The list of shares from which to fill the cache.</param>
/// <param name="options">The current options snapshot.</param>
+ /// <param name="repository">The repository to update.</param>
/// <returns>The operation context.</returns>
- Task ScanAsync(IEnumerable<Share> shares, Options.SharesOptions options);
+ Task ScanAsync(IEnumerable<Share> shares, Options.SharesOptions options, IShareRepository repository);
/// <summary>
/// Cancels the currently running fill operation, if one is running.
@@ -64,16 +65,13 @@ namespace slskd.Shares
/// Initializes a new instance of the <see cref="ShareScanner"/> class.
/// </summary>
/// <param name="workerCount"></param>
- /// <param name="shareRepository"></param>
/// <param name="soulseekFileFactory"></param>
public ShareScanner(
int workerCount,
- IShareRepository shareRepository,
ISoulseekFileFactory soulseekFileFactory = null)
{
WorkerCount = workerCount;
SoulseekFileFactory = soulseekFileFactory ?? new SoulseekFileFactory();
- Repository = shareRepository;
}
/// <summary>
@@ -88,15 +86,15 @@ namespace slskd.Shares
private IManagedState<SharedFileCacheState> State { get; } = new ManagedState<SharedFileCacheState>();
private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1);
private CancellationTokenSource CancellationTokenSource { get; set; }
- private IShareRepository Repository { get; }
/// <summary>
/// Scans the configured shares and fills the cache.
/// </summary>
/// <param name="shares">The list of shares from which to fill the cache.</param>
/// <param name="options">The current options snapshot.</param>
+ /// <param name="repository">The repository to update.</param>
/// <returns>The operation context.</returns>
- public async Task ScanAsync(IEnumerable<Share> shares, Options.SharesOptions options)
+ public async Task ScanAsync(IEnumerable<Share> shares, Options.SharesOptions options, IShareRepository repository)
{
// obtain the semaphore, or fail if it can't be obtained immediately, indicating that a scan is running.
if (!await SyncRoot.WaitAsync(millisecondsTimeout: 0))
@@ -127,10 +125,10 @@ namespace slskd.Shares
// it's possible that the database was tampered with between the time it was checked at startup and now
// validate the tables, and if there's an issue, drop and recreate everything.
- if (!Repository.TryValidate())
+ if (!repository.TryValidate())
{
Log.Warning("Shared file cache missing or invalid. Re-creating prior to scan.");
- Repository.Create(discardExisting: true);
+ repository.Create(discardExisting: true);
Log.Information("Shared file cache re-created and ready for scan.");
}
@@ -142,7 +140,7 @@ namespace slskd.Shares
var timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- Repository.InsertScan(timestamp, options);
+ repository.InsertScan(timestamp, options);
var sw = new Stopwatch();
var swSnapshot = 0L;
@@ -166,7 +164,7 @@ namespace slskd.Shares
Log.Information("Enumerating shared directories");
swSnapshot = sw.ElapsedMilliseconds;
- // derive a list of all directories from all shares skip hidden and system directories, as well as anything that
+ // derive a list of all directories from all shares. skip hidden and system directories, as well as anything that
// can't be accessed due to security restrictions. it's necessary to enumerate these directories up front so we
// can deduplicate directories and apply exclusions
var unmaskedDirectories = Shares
@@ -232,7 +230,7 @@ namespace slskd.Shares
var share = Shares.First(share => directory.StartsWith(share.LocalPath));
- Repository.InsertDirectory(directory.ReplaceFirst(share.LocalPath, share.RemotePath).NormalizePathForSoulseek(), timestamp);
+ repository.InsertDirectory(directory.ReplaceFirst(share.LocalPath, share.RemotePath).NormalizePathForSoulseek(), timestamp);
// recursively find all files in the directory and stick a record in a dictionary, keyed on the sanitized
// filename and with a value of a Soulseek.File object
@@ -262,7 +260,7 @@ namespace slskd.Shares
continue;
}
- Repository.InsertFile(maskedFilename: file.Filename, originalFilename, touchedAt: info.LastWriteTimeUtc, file, timestamp);
+ repository.InsertFile(maskedFilename: file.Filename, originalFilename, touchedAt: info.LastWriteTimeUtc, file, timestamp);
}
}
catch (Exception ex)
@@ -313,13 +311,13 @@ namespace slskd.Shares
Log.Information("Scan found {Files} files (and {Filtered} were filtered) in {Elapsed}ms", cached, filtered, sw.ElapsedMilliseconds - swSnapshot);
swSnapshot = sw.ElapsedMilliseconds;
- var deletedFiles = Repository.PruneFiles(olderThanTimestamp: timestamp);
- var deletedDirectories = Repository.PruneDirectories(olderThanTimestamp: timestamp);
+ var deletedFiles = repository.PruneFiles(olderThanTimestamp: timestamp);
+ var deletedDirectories = repository.PruneDirectories(olderThanTimestamp: timestamp);
Log.Information("Removed or renamed {Files} files and {Directories} directories in {Elapsed}ms", deletedFiles, deletedDirectories, sw.ElapsedMilliseconds - swSnapshot);
Log.Information("Rebuilding filename index...");
- Repository.RebuildFilenameIndex();
+ repository.RebuildFilenameIndex();
Log.Information("Filename index rebuild complete");
}
catch (OperationCanceledException)
@@ -330,10 +328,10 @@ namespace slskd.Shares
State.SetValue(state => state with { Cancelled = true });
}
- Repository.UpdateScan(timestamp, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds());
+ repository.UpdateScan(timestamp, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds());
- var directoryCount = Repository.CountDirectories();
- var fileCount = Repository.CountFiles();
+ var directoryCount = repository.CountDirectories();
+ var fileCount = repository.CountFiles();
State.SetValue(state => state with
{
diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs
index d6c6b977..a497012f 100644
--- a/src/slskd/Shares/ShareService.cs
+++ b/src/slskd/Shares/ShareService.cs
@@ -57,9 +57,7 @@ namespace slskd.Shares
AllRepositories = new List<IShareRepository>(new[] { repository });
- Scanner = scanner ?? new ShareScanner(
- shareRepository: repository,
- workerCount: options.Shares.Cache.Workers);
+ Scanner = scanner ?? new ShareScanner(workerCount: options.Shares.Cache.Workers);
Scanner.StateMonitor.OnChange(cacheState =>
{
@@ -130,6 +128,12 @@ namespace slskd.Shares
AllRepositories = HostDictionary.Values
.Select(value => value.Repository)
.Prepend(Local.Repository);
+
+ State.SetValue(state => state with
+ {
+ Directories = Hosts.Sum(host => host.Shares.Sum(share => share.Directories)),
+ Files = Hosts.Sum(host => host.Shares.Sum(share => share.Directories)),
+ });
}
/// <summary>
@@ -184,6 +188,23 @@ namespace slskd.Shares
}
/// <summary>
+ /// Gets summary information for the specified <paramref name="share"/>.
+ /// </summary>
+ /// <param name="share">The share to summarize.</param>
+ /// <returns>The summary information.</returns>
+ public Task<(int Directories, int Files)> ComputeShareStatisticsAsync(Share share)
+ {
+ var prefix = share.RemotePath + (share.RemotePath.EndsWith('\\') ? string.Empty : '\\');
+
+ var dirs = AllRepositories.Select(r => r.CountDirectories(prefix)).Sum();
+ var files = AllRepositories.Select(r => r.CountFiles(prefix)).Sum();
+
+ share.UpdateStatistics(dirs, files);
+
+ return Task.FromResult((dirs, files));
+ }
+
+ /// <summary>
/// Dumps the local share cache to a file.
/// </summary>
/// <param name="filename">The destination file.</param>
@@ -218,7 +239,20 @@ namespace slskd.Shares
/// <param name="name">The name of the host.</param>
/// <returns>A value indicating whether the host was removed.</returns>
public bool TryRemoveHost(string name)
- => HostDictionary.TryRemove(name, out _);
+ {
+ if (HostDictionary.TryRemove(name, out _))
+ {
+ State.SetValue(state => state with
+ {
+ Directories = Hosts.Sum(host => host.Shares.Sum(share => share.Directories)),
+ Files = Hosts.Sum(host => host.Shares.Sum(share => share.Directories)),
+ });
+
+ return true;
+ }
+
+ return false;
+ }
/// <summary>
/// Returns the contents of the specified <paramref name="directory"/>.
@@ -293,25 +327,15 @@ namespace slskd.Shares
/// <exception cref="ShareScanInProgressException">Thrown when a scan is already in progress.</exception>
public async Task ScanAsync()
{
- await Scanner.ScanAsync(Local.Host.Shares, OptionsMonitor.CurrentValue.Shares);
+ await Scanner.ScanAsync(Local.Host.Shares, OptionsMonitor.CurrentValue.Shares, Local.Repository);
Log.Debug("Backing up shared file cache database...");
Local.Repository.BackupTo(ShareRepositoryFactory.CreateFromHostBackup(Local.Host.Name));
Log.Debug("Shared file cache database backup complete");
- }
- /// <summary>
- /// Gets summary information for the specified <paramref name="share"/>.
- /// </summary>
- /// <param name="share">The share to summarize.</param>
- /// <returns>The summary information.</returns>
- public Task<(int Directories, int Files)> SummarizeShareAsync(Share share)
- {
- var prefix = share.RemotePath + (share.RemotePath.EndsWith('\\') ? string.Empty : '\\');
-
- var dirs = AllRepositories.Select(r => r.CountDirectories(prefix)).Sum();
- var files = AllRepositories.Select(r => r.CountFiles(prefix)).Sum();
- return Task.FromResult((dirs, files));
+ Log.Debug("Recomputing share statistics...");
+ await Task.WhenAll(Local.Host.Shares.Select(share => ComputeShareStatisticsAsync(share)));
+ Log.Debug("Share statistics updated");
}
/// <summary>
@@ -391,6 +415,10 @@ namespace slskd.Shares
Local.Repository.EnableKeepalive(true);
+ Log.Debug("Recomputing share statistics...");
+ await Task.WhenAll(Local.Host.Shares.Select(share => ComputeShareStatisticsAsync(share)));
+ Log.Debug("Share statistics updated");
+
// one of several thigns happened above before we got here:
// this method was called with forceRescan = true
// the storage mode is memory, and we loaded the in-memory db from a valid backup
@@ -404,8 +432,8 @@ namespace slskd.Shares
Faulted = false,
Ready = true,
ScanProgress = 1,
- Directories = Local.Repository.CountDirectories(),
- Files = Local.Repository.CountFiles(),
+ Directories = Hosts.Sum(host => host.Shares.Sum(share => share.Directories)),
+ Files = Hosts.Sum(host => host.Shares.Sum(share => share.Directories)),
});
}
catch (Exception ex)
diff --git a/src/slskd/Shares/Types/Share.cs b/src/slskd/Shares/Types/Share.cs
index 6a6d1f66..42a2e9e2 100644
--- a/src/slskd/Shares/Types/Share.cs
+++ b/src/slskd/Shares/Types/Share.cs
@@ -35,8 +35,10 @@ namespace slskd.Shares
/// <param name="localPath"></param>
/// <param name="raw"></param>
/// <param name="remotePath"></param>
+ /// <param name="directories"></param>
+ /// <param name="files"></param>
[JsonConstructor]
- public Share (string id, string alias, bool isExcluded, string localPath, string raw, string remotePath)
+ public Share (string id, string alias, bool isExcluded, string localPath, string raw, string remotePath, int directories, int files)
{
Id = id;
Alias = alias;
@@ -44,6 +46,8 @@ namespace slskd.Shares
LocalPath = localPath;
Raw = raw;
RemotePath = remotePath;
+ Directories = directories;
+ Files = files;
}
/// <summary>
@@ -87,5 +91,13 @@ namespace slskd.Shares
public string LocalPath { get; init; }
public string Raw { get; init; }
public string RemotePath { get; init; }
+ public int Directories { get; private set; }
+ public int Files { get; private set; }
+
+ public void UpdateStatistics(int directories, int files)
+ {
+ Directories = directories;
+ Files = files;
+ }
}
}
diff --git a/src/web/src/components/System/Shares/ShareTable.js b/src/web/src/components/System/Shares/ShareTable.js
index d264fc8f..095a8380 100644
--- a/src/web/src/components/System/Shares/ShareTable.js
+++ b/src/web/src/components/System/Shares/ShareTable.js
@@ -13,6 +13,7 @@ const ShareTable = ({ shares, onClick }) => {
<Table>
<Table.Header>
<Table.Row>
+ <Table.HeaderCell>Host</Table.HeaderCell>
<Table.HeaderCell>Local Path</Table.HeaderCell>
<Table.HeaderCell className='share-count-column'>Directories</Table.HeaderCell>
<Table.HeaderCell className='share-count-column'>Files</Table.HeaderCell>
@@ -29,6 +30,7 @@ const ShareTable = ({ shares, onClick }) => {
</Table.Row>}
>
{shares.map((share, index) => (<Table.Row key={index}>
+ <Table.Cell>{share.host}</Table.Cell>
<Table.Cell onClick={() => onClick(share)}>
<Icon name='folder'/>
<Link to='#'>{share.localPath}</Link>
diff --git a/src/web/src/components/System/Shares/index.js b/src/web/src/components/System/Shares/index.js
index 6759ad6f..f4f9ac94 100644
--- a/src/web/src/components/System/Shares/index.js
+++ b/src/web/src/components/System/Shares/index.js
@@ -39,7 +39,13 @@ const Index = ({ state = {} } = {}) => {
const getAll = async () => {
try {
setLoading(true);
- setShares(await sharesLib.getAll());
+
+ const sharesByHost = await sharesLib.getAll();
+ const flattened = Object.entries(sharesByHost).reduce((acc, [host, shares]) => {
+ return acc.concat(shares.map(share => ({ host, ...share })));
+ }, []);
+
+ setShares(flattened);
} catch (error) {
console.error(error);
toast.error(error?.response?.data ?? error?.message ?? error);