diff options
| author | JP Dillingham <jp@dillingham.me> | 2022-05-29 22:44:53 -0500 |
|---|---|---|
| committer | JP Dillingham <jp@dillingham.me> | 2022-05-29 22:44:53 -0500 |
| commit | 38255041d2e68a6fee1f481b3922869d9b577510 (patch) | |
| tree | 5fd4f80a9251d2f10234df70ec43d374008e242a /src | |
| parent | b9df49674ce5fe359402421f98591a833c31b741 (diff) | |
| download | slskd-38255041d2e68a6fee1f481b3922869d9b577510.tar.gz | |
refactor shares service/cache
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Application.cs | 59 | ||||
| -rw-r--r-- | src/slskd/Program.cs | 1 | ||||
| -rw-r--r-- | src/slskd/Shares/API/Controllers/SharesController.cs | 27 | ||||
| -rw-r--r-- | src/slskd/Shares/ShareService.cs | 72 | ||||
| -rw-r--r-- | src/slskd/Shares/SharesCache.cs (renamed from src/slskd/Shares/SharedFileCache.cs) | 22 | ||||
| -rw-r--r-- | src/slskd/Shares/SoulseekFileFactory.cs | 2 | ||||
| -rw-r--r-- | src/slskd/State.cs | 68 |
7 files changed, 152 insertions, 99 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index c2a8632b..c0390c5a 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -82,7 +82,7 @@ namespace slskd IRoomTracker roomTracker, IRoomService roomService, IUserService userService, - ISharedFileCache sharedFileCache, + IShareService shareService, IPushbulletService pushbulletService, IHubContext<ApplicationHub> applicationHub, IHubContext<LogsHub> logHub) @@ -97,8 +97,8 @@ namespace slskd State = state; State.OnChange(state => State_OnChange(state)); - SharedFileCache = sharedFileCache; - SharedFileCache.StateMonitor.OnChange(state => SharedFileCacheState_OnChange(state)); + Shares = shareService; + Shares.StateMonitor.OnChange(state => ShareState_OnChange(state)); TransferTracker = transferTracker; Transfers = transferService; @@ -152,7 +152,6 @@ namespace slskd private SemaphoreSlim OptionsSyncRoot { get; } = new SemaphoreSlim(1, 1); private Options PreviousOptions { get; set; } private IPushbulletService Pushbullet { get; } - private ISharedFileCache SharedFileCache { get; set; } private DateTime SharesRefreshStarted { get; set; } private IManagedState<State> State { get; } private ITransferTracker TransferTracker { get; set; } @@ -160,6 +159,7 @@ namespace slskd private IHubContext<ApplicationHub> ApplicationHub { get; set; } private IHubContext<LogsHub> LogHub { get; set; } private IUserService Users { get; set; } + private IShareService Shares { get; set; } public void CollectGarbage() { @@ -306,7 +306,7 @@ namespace slskd } else { - _ = SharedFileCache.FillAsync(); + _ = Shares.StartScanAsync(); } if (OptionsAtStartup.NoConnect) @@ -337,12 +337,12 @@ namespace slskd /// <param name="username">The username of the requesting user.</param> /// <param name="endpoint">The IP endpoint of the requesting user.</param> /// <returns>A Task resolving an IEnumerable of Soulseek.Directory.</returns> - private Task<BrowseResponse> BrowseResponseResolver(string username, IPEndPoint endpoint) + private async Task<BrowseResponse> BrowseResponseResolver(string username, IPEndPoint endpoint) { - var directories = SharedFileCache.Browse() + var directories = (await Shares.BrowseAsync()) .Select(d => new Soulseek.Directory(d.Name.Replace('/', '\\'), d.Files)); // Soulseek NS requires backslashes - return Task.FromResult(new BrowseResponse(directories)); + return new BrowseResponse(directories); } private void Client_BrowseProgressUpdated(object sender, BrowseProgressUpdatedEventArgs args) @@ -441,7 +441,7 @@ namespace slskd // send whatever counts we have currently. we'll probably connect before the cache is primed, so these will be zero // initially, but we'll update them when the cache is filled. - _ = Client.SetSharedCountsAsync(State.CurrentValue.SharedFileCache.Directories, State.CurrentValue.SharedFileCache.Files); + _ = Client.SetSharedCountsAsync(State.CurrentValue.Shares.Cache.Directories, State.CurrentValue.Shares.Cache.Files); } private void Client_PrivateMessageRecieved(object sender, PrivateMessageReceivedEventArgs args) @@ -553,10 +553,10 @@ namespace slskd /// <param name="token">The unique token for the request, supplied by the requesting user.</param> /// <param name="directory">The requested directory.</param> /// <returns>A Task resolving an instance of Soulseek.Directory containing the contents of the requested directory.</returns> - private Task<Soulseek.Directory> DirectoryContentsResponseResolver(string username, IPEndPoint endpoint, int token, string directory) + private async Task<Soulseek.Directory> DirectoryContentsResponseResolver(string username, IPEndPoint endpoint, int token, string directory) { - var dir = SharedFileCache.List(directory); - return Task.FromResult(dir); + var dir = await Shares.ListAsync(directory); + return dir; } /// <summary> @@ -574,10 +574,10 @@ namespace slskd /// Thrown on any other Exception other than a rejection. A generic message will be passed to the remote user for /// security reasons. /// </exception> - private Task EnqueueDownloadAction(string username, IPEndPoint endpoint, string filename, ITransferTracker tracker) + private async Task EnqueueDownloadAction(string username, IPEndPoint endpoint, string filename, ITransferTracker tracker) { _ = endpoint; - var localFilename = SharedFileCache.Resolve(filename).ToLocalOSPath(); + var localFilename = (await Shares.ResolveAsync(filename)).ToLocalOSPath(); var fileInfo = new FileInfo(localFilename); @@ -593,7 +593,7 @@ namespace slskd { // in this case, a re-requested file is a no-op. normally we'd want to respond with a PlaceInQueueResponse Console.WriteLine($"[UPLOAD RE-REQUESTED] [{username}/{filename}]"); - return Task.CompletedTask; + return; } // create a new cancellation token source so that we can cancel the upload from the UI. @@ -632,9 +632,6 @@ namespace slskd { Console.WriteLine($"[UPLOAD FAILED] {t.Exception}"); }, TaskContinuationOptions.NotOnRanToCompletion); // fire and forget - - // return a completed task so that the invoking code can respond to the remote client. - return Task.CompletedTask; } private async Task OptionsMonitor_OnChange(Options newOptions) @@ -819,7 +816,7 @@ namespace slskd return null; } - var results = await SharedFileCache.SearchAsync(query); + var results = await Shares.SearchAsync(query); if (results.Any()) { @@ -839,45 +836,45 @@ namespace slskd return null; } - private void SharedFileCacheState_OnChange((SharedFileCacheState Previous, SharedFileCacheState Current) state) + private void ShareState_OnChange((ShareState Previous, ShareState Current) state) { var (previous, current) = state; - if (!previous.Filling && current.Filling) + if (!previous.Cache.Filling && current.Cache.Filling) { SharesRefreshStarted = DateTime.UtcNow; - State.SetValue(s => s with { SharedFileCache = current }); + State.SetValue(s => s with { Shares = current }); Log.Information("Scanning shares"); } - var lastProgress = Math.Round(previous.FillProgress * 100); - var currentProgress = Math.Round(current.FillProgress * 100); + var lastProgress = Math.Round(previous.Cache.FillProgress * 100); + var currentProgress = Math.Round(current.Cache.FillProgress * 100); if (lastProgress != currentProgress && Math.Round(currentProgress, 0) % 10 == 0) { - State.SetValue(s => s with { SharedFileCache = current }); - Log.Information("Scanned {Percent}% of shared directories. Found {Files} files so far.", currentProgress, current.Files); + State.SetValue(s => s with { Shares = current }); + Log.Information("Scanned {Percent}% of shared directories. Found {Files} files so far.", currentProgress, current.Cache.Files); } - if (previous.Filling && !current.Filling) + if (previous.Cache.Filling && !current.Cache.Filling) { - State.SetValue(s => s with { SharedFileCache = current }); + State.SetValue(s => s with { Shares = current }); - if (current.Faulted) + if (current.Cache.Faulted) { Log.Error("Failed to scan shares."); } else { State.SetValue(s => s with { PendingShareRescan = false }); - Log.Information("Shares scanned successfully. Found {Directories} directories and {Files} files in {Duration}ms", current.Directories, current.Files, (DateTime.UtcNow - SharesRefreshStarted).TotalMilliseconds); + Log.Information("Shares scanned successfully. Found {Directories} directories and {Files} files in {Duration}ms", current.Cache.Directories, current.Cache.Files, (DateTime.UtcNow - SharesRefreshStarted).TotalMilliseconds); SharesRefreshStarted = default; if (Client.State.HasFlag(SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn)) { - _ = Client.SetSharedCountsAsync(State.CurrentValue.SharedFileCache.Directories, State.CurrentValue.SharedFileCache.Files); + _ = Client.SetSharedCountsAsync(State.CurrentValue.Shares.Cache.Directories, State.CurrentValue.Shares.Cache.Files); } } } diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 4643daa0..1a5d2a28 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -453,7 +453,6 @@ namespace slskd services.AddSingleton<IConversationTracker, ConversationTracker>(); services.AddSingleton<IRoomTracker, RoomTracker>(_ => new RoomTracker(messageLimit: 250)); - services.AddSingleton<ISharedFileCache, SharedFileCache>(); services.AddSingleton<IShareService, ShareService>(); services.AddSingleton<ISearchService, SearchService>(); diff --git a/src/slskd/Shares/API/Controllers/SharesController.cs b/src/slskd/Shares/API/Controllers/SharesController.cs index 0b397bfd..251f50b9 100644 --- a/src/slskd/Shares/API/Controllers/SharesController.cs +++ b/src/slskd/Shares/API/Controllers/SharesController.cs @@ -19,6 +19,7 @@ namespace slskd.Shares.API { using System.Collections.Generic; using System.Linq; + using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; @@ -57,11 +58,11 @@ namespace slskd.Shares.API [HttpGet("")] [Authorize] [ProducesResponseType(typeof(IEnumerable<SummarizedShare>), 200)] - public IActionResult List() + public async Task<IActionResult> List() { - var browse = Shares.Cache.Browse(); + var browse = await Shares.BrowseAsync(); - var summary = Shares.Cache.Shares.Select(share => + var summary = Shares.Shares.Select(share => { var directories = browse.Where(directory => directory.Name.StartsWith(share.RemotePath)); var fileCount = directories.Aggregate(seed: 0, (sum, directory) => @@ -98,16 +99,16 @@ namespace slskd.Shares.API [Authorize] [ProducesResponseType(typeof(SummarizedShare), 200)] [ProducesResponseType(404)] - public IActionResult Get(string id) + public async Task<IActionResult> Get(string id) { - var share = Shares.Cache.Shares.FirstOrDefault(share => share.Id == id); + var share = Shares.Shares.FirstOrDefault(share => share.Id == id); if (share == default) { return NotFound(); } - var browse = Shares.Cache.Browse(); + var browse = await Shares.BrowseAsync(); var directories = browse.Where(directory => directory.Name.StartsWith(share.RemotePath)); var fileCount = directories.Aggregate(seed: 0, (sum, directory) => { @@ -139,9 +140,9 @@ namespace slskd.Shares.API [HttpGet("contents")] [Authorize] [ProducesResponseType(typeof(IEnumerable<Soulseek.Directory>), 200)] - public IActionResult BrowseAll() + public async Task<IActionResult> BrowseAll() { - return Ok(Shares.Cache.Browse()); + return Ok(await Shares.BrowseAsync()); } /// <summary> @@ -154,16 +155,16 @@ namespace slskd.Shares.API [HttpGet("{id}/contents")] [ProducesResponseType(typeof(IEnumerable<Soulseek.Directory>), 200)] [ProducesResponseType(404)] - public IActionResult BrowseShare(string id) + public async Task<IActionResult> BrowseShare(string id) { - var share = Shares.Cache.Shares.FirstOrDefault(share => share.Id == id); + var share = Shares.Shares.FirstOrDefault(share => share.Id == id); if (share == default) { return NotFound(); } - var contents = Shares.Cache.Browse() + var contents = (await Shares.BrowseAsync()) .Where(directory => directory.Name.StartsWith(share.RemotePath)); return Ok(contents); @@ -182,12 +183,12 @@ namespace slskd.Shares.API [ProducesResponseType(409)] public IActionResult RescanSharesAsync() { - if (ApplicationStateMonitor.CurrentValue.SharedFileCache.Filling) + if (ApplicationStateMonitor.CurrentValue.Shares.Cache.Filling) { return Conflict("A share scan is already in progress."); } - _ = Shares.Cache.FillAsync(); + _ = Shares.StartScanAsync(); return Ok(); } diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index 763bb819..68b3c629 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -1,3 +1,20 @@ +// <copyright file="ShareService.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> + using Microsoft.Extensions.Options; namespace slskd.Shares @@ -5,31 +22,64 @@ namespace slskd.Shares using System; using System.Collections.Generic; using System.Linq; + using System.Threading.Tasks; + using Soulseek; public interface IShareService { - ISharedFileCache Cache { get; } - IReadOnlyList<Share> List(Func<Share, bool> expression = null); + IReadOnlyList<Share> Shares { get; } + + Task<IEnumerable<Soulseek.Directory>> BrowseAsync(); + + Task<Directory> ListAsync(string directory); + + Task<IEnumerable<File>> SearchAsync(SearchQuery query); + + Task StartScanAsync(); + + Task<string> ResolveAsync(string remoteFilename); + + public IStateMonitor<ShareState> StateMonitor { get; } } public class ShareService : IShareService { public ShareService( - ISharedFileCache sharedFileCache, - IOptionsMonitor<Options> optionsMonitor) + IOptionsMonitor<Options> optionsMonitor, + IShareCache sharesCache = null) { - Cache = sharedFileCache; OptionsMonitor = optionsMonitor; + + // todo: when options change, fill SharesList with configured shares + // and set ScanPending = true + + Cache = sharesCache ?? new ShareCache(OptionsMonitor); + Cache.StateMonitor.OnChange(cacheState + => State.SetValue(state + => state with { Cache = cacheState.Current })); } - public ISharedFileCache Cache { get; } + public IReadOnlyList<Share> Shares => SharesList.AsReadOnly(); + public IStateMonitor<ShareState> StateMonitor => State; + private IShareCache Cache { get; } private IOptionsMonitor<Options> OptionsMonitor { get; } - private List<Share> Shares { get; set; } = new List<Share>(); + private List<Share> SharesList { get; set; } = new List<Share>(); + private IManagedState<ShareState> State { get; } = new ManagedState<ShareState>(); - public IReadOnlyList<Share> List(Func<Share, bool> expression = null) - { - return Shares.Where(expression).ToList().AsReadOnly(); - } + public Task<IEnumerable<Soulseek.Directory>> BrowseAsync() + => Task.FromResult(Cache.Browse()); + + public Task<Soulseek.Directory> ListAsync(string directory) + => Task.FromResult(Cache.List(directory)); + + public Task<IEnumerable<Soulseek.File>> SearchAsync(SearchQuery query) + => Cache.SearchAsync(query); + + public Task StartScanAsync() + => Cache.FillAsync(); + + public Task<string> ResolveAsync(string remoteFilename) + => Task.FromResult(Cache.Resolve(remoteFilename)); } }
\ No newline at end of file diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharesCache.cs index 5a218835..22e72c77 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharesCache.cs @@ -1,4 +1,4 @@ -// <copyright file="SharedFileCache.cs" company="slskd Team"> +// <copyright file="ISharesCache.cs" company="slskd Team"> // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -35,17 +35,17 @@ namespace slskd.Shares /// <summary> /// Shared file cache. /// </summary> - public interface ISharedFileCache + public interface IShareCache { /// <summary> /// Gets the list of shares. /// </summary> - public List<Share> Shares { get; } + public List<Share> Shares { get; } // todo: remove this /// <summary> /// Gets the cache state monitor. /// </summary> - IStateMonitor<SharedFileCacheState> StateMonitor { get; } + IStateMonitor<ShareState.ShareCacheState> StateMonitor { get; } /// <summary> /// Returns the contents of the cache. @@ -57,7 +57,7 @@ namespace slskd.Shares /// Scans the configured shares and fills the cache. /// </summary> /// <returns>The operation context.</returns> - Task FillAsync(); + Task FillAsync(); // TODO: accept a list of shares here /// <summary> /// Returns the contents of the specified <paramref name="directory"/>. @@ -85,14 +85,14 @@ namespace slskd.Shares /// <summary> /// Shared file cache. /// </summary> - public class SharedFileCache : ISharedFileCache + public class ShareCache : IShareCache { /// <summary> - /// Initializes a new instance of the <see cref="SharedFileCache"/> class. + /// Initializes a new instance of the <see cref="ShareCache"/> class. /// </summary> /// <param name="optionsMonitor"></param> /// <param name="soulseekFileFactory"></param> - public SharedFileCache( + public ShareCache( IOptionsMonitor<Options> optionsMonitor, ISoulseekFileFactory soulseekFileFactory = null) { @@ -103,15 +103,15 @@ namespace slskd.Shares /// <summary> /// Gets the cache state monitor. /// </summary> - public IStateMonitor<SharedFileCacheState> StateMonitor => State; + public IStateMonitor<ShareState.ShareCacheState> StateMonitor => State; /// <summary> /// Gets the list of shares. /// </summary> public List<Share> Shares { get; private set; } - private IManagedState<SharedFileCacheState> State { get; } = new ManagedState<SharedFileCacheState>(); - private ILogger Log { get; } = Serilog.Log.ForContext<SharedFileCache>(); + private IManagedState<ShareState.ShareCacheState> State { get; } = new ManagedState<ShareState.ShareCacheState>(); + private ILogger Log { get; } = Serilog.Log.ForContext<ShareCache>(); private HashSet<string> MaskedDirectories { get; set; } private Dictionary<string, File> MaskedFiles { get; set; } private IOptionsMonitor<Options> OptionsMonitor { get; set; } diff --git a/src/slskd/Shares/SoulseekFileFactory.cs b/src/slskd/Shares/SoulseekFileFactory.cs index 5221265b..7cdd6174 100644 --- a/src/slskd/Shares/SoulseekFileFactory.cs +++ b/src/slskd/Shares/SoulseekFileFactory.cs @@ -48,7 +48,7 @@ namespace slskd.Shares private static readonly string[] VideoExtensions = { "mkv", "ogv", "avi", "wmv", "asf", "mp4", "m4p", "m4v", "mpg", "mpe", "mpv", "mpg", "m2v" }; private static readonly HashSet<string> SupportedExtensions = AudioExtensions.Concat(VideoExtensions).ToHashSet(); - private ILogger Log { get; } = Serilog.Log.ForContext<SharedFileCache>(); + private ILogger Log { get; } = Serilog.Log.ForContext<SoulseekFileFactory>(); /// <summary> /// Creates an instance of <see cref="Soulseek.File"/> from the given path. diff --git a/src/slskd/State.cs b/src/slskd/State.cs index 0daa5d76..b84efb6c 100644 --- a/src/slskd/State.cs +++ b/src/slskd/State.cs @@ -35,7 +35,7 @@ namespace slskd public bool PendingShareRescan { get; init; } public ServerState Server { get; init; } = new ServerState(); public DistributedNetworkState DistributedNetwork { get; init; } = new DistributedNetworkState(); - public SharedFileCacheState SharedFileCache { get; init; } = new SharedFileCacheState(); + public ShareState Shares { get; init; } = new ShareState(); public string[] Rooms { get; init; } = Array.Empty<string>(); public User[] Users { get; init; } = Array.Empty<User>(); } @@ -76,43 +76,49 @@ namespace slskd } /// <summary> - /// Share cache state. + /// Share state. /// </summary> - public record SharedFileCacheState + public record ShareState { - /// <summary> - /// Gets a value indicating whether the cache is being filled. - /// </summary> - public bool Filling { get; init; } = false; + public ShareCacheState Cache { get; init; } = new ShareCacheState(); + public bool ScanPending { get; init; } - /// <summary> - /// Gets a value indicating whether the cache is filled. - /// </summary> - public bool Filled { get; init; } = false; + public record ShareCacheState + { + /// <summary> + /// Gets a value indicating whether the cache is being filled. + /// </summary> + public bool Filling { get; init; } = false; - /// <summary> - /// Gets a value indicating whether the cache is faulted. - /// </summary> - public bool Faulted { get; init; } = false; + /// <summary> + /// Gets a value indicating whether the cache is filled. + /// </summary> + public bool Filled { get; init; } = false; - /// <summary> - /// Gets the current fill progress. - /// </summary> - public double FillProgress { get; init; } + /// <summary> + /// Gets a value indicating whether the cache is faulted. + /// </summary> + public bool Faulted { get; init; } = false; - /// <summary> - /// Gets the number of cached directories. - /// </summary> - public int Directories { get; init; } + /// <summary> + /// Gets the current fill progress. + /// </summary> + public double FillProgress { get; init; } - /// <summary> - /// Gets the number of cached files. - /// </summary> - public int Files { get; init; } + /// <summary> + /// Gets the number of cached directories. + /// </summary> + public int Directories { get; init; } - /// <summary> - /// Gets the number of directories excluded by filters. - /// </summary> - public int ExcludedDirectories { get; init; } + /// <summary> + /// Gets the number of cached files. + /// </summary> + public int Files { get; init; } + + /// <summary> + /// Gets the number of directories excluded by filters. + /// </summary> + public int ExcludedDirectories { get; init; } + } } }
\ No newline at end of file |
