diff options
| author | JP Dillingham <jp@dillingham.me> | 2022-05-17 10:55:31 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2022-05-17 10:55:31 -0500 |
| commit | 8ea2d8a4d88180a103081cce7a425c2bb6172b03 (patch) | |
| tree | 7292443fa34f2cca21c432ed338d9013aa240d84 /src/slskd | |
| parent | 978d0d08ab34a9e5dd0211de1d242a264b17577e (diff) | |
| parent | daf5e72ad63109978eeef2d0c4377b942f6209cb (diff) | |
| download | slskd-8ea2d8a4d88180a103081cce7a425c2bb6172b03.tar.gz | |
Merge branch 'master' into dependabot/npm_and_yarn/src/web/ejs-3.1.8
Diffstat (limited to 'src/slskd')
| -rw-r--r-- | src/slskd/Common/RateLimiter.cs | 97 | ||||
| -rw-r--r-- | src/slskd/Program.cs | 5 | ||||
| -rw-r--r-- | src/slskd/Search/API/Controllers/SearchesController.cs | 55 | ||||
| -rw-r--r-- | src/slskd/Search/API/Hubs/SearchHub.cs | 30 | ||||
| -rw-r--r-- | src/slskd/Search/Domain/Search.cs | 2 | ||||
| -rw-r--r-- | src/slskd/Search/Extensions.cs | 16 | ||||
| -rw-r--r-- | src/slskd/Search/ISearchService.cs | 7 | ||||
| -rw-r--r-- | src/slskd/Search/SearchService.cs | 155 |
8 files changed, 278 insertions, 89 deletions
diff --git a/src/slskd/Common/RateLimiter.cs b/src/slskd/Common/RateLimiter.cs new file mode 100644 index 00000000..a5d1ba45 --- /dev/null +++ b/src/slskd/Common/RateLimiter.cs @@ -0,0 +1,97 @@ +// <copyright file="RateLimiter.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 +{ + using System; + using System.ComponentModel; + + /// <summary> + /// Ensures a minimum interval between successive invocations of a delegate. + /// </summary> + public class RateLimiter : IDisposable + { + /// <summary> + /// Initializes a new instance of the <see cref="RateLimiter"/> class. + /// </summary> + /// <param name="interval">The minimum interval between invocations.</param> + public RateLimiter(int interval) + { + Timer = new System.Timers.Timer(interval) + { + AutoReset = true, + }; + + Timer.Elapsed += (s, e) => + { + Staged?.Invoke(); + Staged = null; + }; + } + + private bool Disposed { get; set; } + private bool Init { get; set; } + private Action Staged { get; set; } + private System.Timers.Timer Timer { get; set; } + + /// <summary> + /// Releases all resources used by the <see cref="Component"/>. + /// </summary> + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + /// <summary> + /// Invokes the specified <paramref name="action"/>, dropping invocations created prior to the elapse of the + /// configured interval. + /// </summary> + /// <param name="action">The delegate to invoke.</param> + public void Invoke(Action action) + { + if (!Init) + { + Init = true; + Timer.Start(); + action(); + return; + } + + Staged = action; + } + + /// <summary> + /// Releases all resources used by the <see cref="Component"/>. + /// </summary> + protected virtual void Dispose(bool disposing) + { + if (!Disposed) + { + if (disposing) + { + // if an action is staged, invoke it to 'flush' + Staged?.Invoke(); + + Timer.Dispose(); + } + + Disposed = true; + } + } + } +}
\ No newline at end of file diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 66fe9762..40e6e72d 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -471,10 +471,11 @@ namespace slskd private static IServiceCollection ConfigureAspDotNetServices(this IServiceCollection services) { services.AddCors(options => options.AddPolicy("AllowAll", builder => builder + .SetIsOriginAllowed((host) => true) .AllowAnyHeader() .AllowAnyMethod() - .SetIsOriginAllowed((host) => true) - .AllowCredentials())); + .AllowCredentials() + .WithExposedHeaders("X-URL-Base"))); services.AddDataProtection() .PersistKeysToFileSystem(new DirectoryInfo(Path.Combine(AppDirectory, "data", ".DataProtection-Keys"))); diff --git a/src/slskd/Search/API/Controllers/SearchesController.cs b/src/slskd/Search/API/Controllers/SearchesController.cs index 5f740044..ae0f6570 100644 --- a/src/slskd/Search/API/Controllers/SearchesController.cs +++ b/src/slskd/Search/API/Controllers/SearchesController.cs @@ -129,7 +129,60 @@ namespace slskd.Search.API [Authorize] public async Task<IActionResult> GetAll() { - return Ok(await Searches.ListAsync()); + var searches = await Searches.ListAsync(); + return Ok(searches); + } + + /// <summary> + /// Stops the search corresponding to the specified <paramref name="id"/>. + /// </summary> + /// <param name="id">The unique id of the search.</param> + /// <response code="200">The search was stopped.</response> + /// <response code="304">The search was not in progress.</response> + /// <returns></returns> + [HttpPut("{id}")] + [Authorize] + [ProducesResponseType(200)] + [ProducesResponseType(304)] + public async Task<IActionResult> Cancel([FromRoute] Guid id) + { + var search = await Searches.FindAsync(search => search.Id == id); + + if (search == default) + { + return NotFound(); + } + + if (Searches.TryCancel(id)) + { + return Ok(); + } + + return StatusCode(304); + } + + /// <summary> + /// Deletes the search corresponding to the specified <paramref name="id"/>. + /// </summary> + /// <param name="id">The unique id of the search.</param> + /// <response code="204">The search was deleted.</response> + /// <response code="404">A search with the specified id could not be found.</response> + /// <returns></returns> + [HttpDelete("{id}")] + [Authorize] + [ProducesResponseType(204)] + [ProducesResponseType(404)] + public async Task<IActionResult> Delete([FromRoute] Guid id) + { + var search = await Searches.FindAsync(search => search.Id == id, includeResponses: true); + + if (search == default) + { + return NotFound(); + } + + await Searches.DeleteAsync(search); + return NoContent(); } } } diff --git a/src/slskd/Search/API/Hubs/SearchHub.cs b/src/slskd/Search/API/Hubs/SearchHub.cs index 86434669..aaf9a287 100644 --- a/src/slskd/Search/API/Hubs/SearchHub.cs +++ b/src/slskd/Search/API/Hubs/SearchHub.cs @@ -15,8 +15,6 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> -using Microsoft.Extensions.Options; - namespace slskd.Search.API { using System; @@ -26,8 +24,11 @@ namespace slskd.Search.API public static class SearchHubMethods { + public static readonly string List = "LIST"; + public static readonly string Create = "CREATE"; public static readonly string Response = "RESPONSE"; public static readonly string Update = "UPDATE"; + public static readonly string Delete = "DELETE"; } /// <summary> @@ -57,6 +58,16 @@ namespace slskd.Search.API { return hub.Clients.All.SendAsync(SearchHubMethods.Response, new { searchId, response }); } + + public static Task BroadcastCreateAsync(this IHubContext<SearchHub> hub, Search search) + { + return hub.Clients.All.SendAsync(SearchHubMethods.Create, search); + } + + public static Task BroadcastDeleteAsync(this IHubContext<SearchHub> hub, Search search) + { + return hub.Clients.All.SendAsync(SearchHubMethods.Delete, search); + } } /// <summary> @@ -66,14 +77,17 @@ namespace slskd.Search.API public class SearchHub : Hub { public SearchHub( - IStateMonitor<State> stateMonitor, - IOptionsMonitor<Options> optionsMonitor) + ISearchService searchService) { - StateMonitor = stateMonitor; - OptionsMonitor = optionsMonitor; + Searches = searchService; } - private IStateMonitor<State> StateMonitor { get; } - private IOptionsMonitor<Options> OptionsMonitor { get; } + private ISearchService Searches { get; } + + public override async Task OnConnectedAsync() + { + var searches = await Searches.ListAsync(); + await Clients.Caller.SendAsync(SearchHubMethods.List, searches); + } } }
\ No newline at end of file diff --git a/src/slskd/Search/Domain/Search.cs b/src/slskd/Search/Domain/Search.cs index b93c62cb..52f97075 100644 --- a/src/slskd/Search/Domain/Search.cs +++ b/src/slskd/Search/Domain/Search.cs @@ -53,7 +53,7 @@ namespace slskd.Search } public string SearchText { get; init; } - public DateTime StartedAt { get; init; } = DateTime.UtcNow; + public DateTime StartedAt { get; init; } = DateTime.Now; public SearchStates State { get; set; } public int Token { get; init; } } diff --git a/src/slskd/Search/Extensions.cs b/src/slskd/Search/Extensions.cs index 149e0a14..b43c3e68 100644 --- a/src/slskd/Search/Extensions.cs +++ b/src/slskd/Search/Extensions.cs @@ -118,5 +118,21 @@ namespace slskd.Search Token = s.Token, }); } + + public static Search WithSoulseekSearch(this Search search, Soulseek.Search s) + { + return new Search() + { + Id = search.Id, + StartedAt = search.StartedAt, + EndedAt = search.EndedAt, + FileCount = s.FileCount, + LockedFileCount = s.LockedFileCount, + ResponseCount = s.ResponseCount, + SearchText = search.SearchText, + State = s.State, + Token = search.Token, + }; + } } } diff --git a/src/slskd/Search/ISearchService.cs b/src/slskd/Search/ISearchService.cs index d696617d..d2cac32e 100644 --- a/src/slskd/Search/ISearchService.cs +++ b/src/slskd/Search/ISearchService.cs @@ -41,6 +41,13 @@ namespace slskd.Search Task<Search> CreateAsync(Guid id, SearchQuery query, SearchScope scope, SearchOptions options = null); /// <summary> + /// Deletes the specified ssearch. + /// </summary> + /// <param name="search">The search to delete.</param> + /// <returns>The operation context.</returns> + Task DeleteAsync(Search search); + + /// <summary> /// Finds a single search matching the specified <paramref name="expression"/>. /// </summary> /// <param name="expression">The expression to use to match searches.</param> diff --git a/src/slskd/Search/SearchService.cs b/src/slskd/Search/SearchService.cs index 1eb92bc2..57d5e321 100644 --- a/src/slskd/Search/SearchService.cs +++ b/src/slskd/Search/SearchService.cs @@ -28,14 +28,13 @@ namespace slskd.Search using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR; using Microsoft.EntityFrameworkCore; - using Microsoft.Extensions.Logging; + using Serilog; using slskd.Search.API; using Soulseek; using SearchOptions = Soulseek.SearchOptions; using SearchQuery = Soulseek.SearchQuery; using SearchScope = Soulseek.SearchScope; using SearchStates = Soulseek.SearchStates; - using SoulseekSearch = Soulseek.Search; /// <summary> /// Handles the lifecycle and persistence of searches. @@ -48,33 +47,27 @@ namespace slskd.Search /// <param name="searchHub"></param> /// <param name="optionsMonitor"></param> /// <param name="soulseekClient"></param> - /// <param name="application"></param> /// <param name="contextFactory">The database context to use.</param> /// <param name="log">The logger.</param> public SearchService( IHubContext<SearchHub> searchHub, IOptionsMonitor<Options> optionsMonitor, ISoulseekClient soulseekClient, - IApplication application, - IDbContextFactory<SearchDbContext> contextFactory, - ILogger<SearchService> log) + IDbContextFactory<SearchDbContext> contextFactory) { SearchHub = searchHub; OptionsMonitor = optionsMonitor; Client = soulseekClient; - Application = application; ContextFactory = contextFactory; - Log = log; } private ConcurrentDictionary<Guid, CancellationTokenSource> CancellationTokens { get; } = new ConcurrentDictionary<Guid, CancellationTokenSource>(); - private IOptionsMonitor<Options> OptionsMonitor { get; } - private IApplication Application { get; } private ISoulseekClient Client { get; } private IDbContextFactory<SearchDbContext> ContextFactory { get; } - private ILogger<SearchService> Log { get; set; } + private ILogger Log { get; set; } = Serilog.Log.ForContext<Application>(); + private IOptionsMonitor<Options> OptionsMonitor { get; } private IHubContext<SearchHub> SearchHub { get; set; } /// <summary> @@ -88,7 +81,11 @@ namespace slskd.Search public async Task<Search> CreateAsync(Guid id, SearchQuery query, SearchScope scope, SearchOptions options = null) { var token = Client.GetNextToken(); + var cancellationTokenSource = new CancellationTokenSource(); + CancellationTokens.TryAdd(id, cancellationTokenSource); + + var rateLimiter = new RateLimiter(250); var search = new Search() { @@ -96,52 +93,86 @@ namespace slskd.Search Token = token, Id = id, State = SearchStates.Requested, - StartedAt = DateTime.UtcNow, + StartedAt = DateTime.Now, }; - options ??= new SearchOptions(); - options = options.WithActions( - stateChanged: (args) => UpdateSearchState(search, args.Search), - responseReceived: (args) => UpdateSearchResponses(search, args.Search, args.Response)); + using var context = ContextFactory.CreateDbContext(); + context.Add(search); + await context.SaveChangesAsync(); + await SearchHub.BroadcastCreateAsync(search); + + List<SearchResponse> responses = new(); - try + _ = Task.Run(async () => { - using var context = ContextFactory.CreateDbContext(); + try + { + options ??= new SearchOptions(); + options = options.WithActions( + stateChanged: (args) => + { + search = search.WithSoulseekSearch(args.Search); + SearchHub.BroadcastUpdateAsync(search); + }, + responseReceived: (args) => + rateLimiter.Invoke(() => SearchHub.BroadcastUpdateAsync(search.WithSoulseekSearch(args.Search)))); + + var soulseekSearch = await Client.SearchAsync( + query, + responseReceived: (response) => responses.Add(response), + scope, + token, + options, + cancellationToken: cancellationTokenSource.Token); + + search = search.WithSoulseekSearch(soulseekSearch); + } + finally + { + rateLimiter.Dispose(); + CancellationTokens.TryRemove(id, out _); + + try + { + using var context = ContextFactory.CreateDbContext(); - context.Add(search); - await context.SaveChangesAsync(); + search.EndedAt = DateTime.Now; + search.Responses = responses.Select(r => Response.FromSoulseekSearchResponse(r)); - CancellationTokens.TryAdd(id, cancellationTokenSource); - var responses = new List<Response>(); + context.Update(search); + await context.SaveChangesAsync(); - var soulseekSearch = await Client.SearchAsync( - query, - responseReceived: (response) => + // zero responses before broadcasting + search.Responses = Enumerable.Empty<Response>(); + await SearchHub.BroadcastUpdateAsync(search); + } + catch (Exception ex) { - responses.Add(Response.FromSoulseekSearchResponse(response)); - }, - scope, - token, - options, - cancellationToken: cancellationTokenSource.Token); - - CancellationTokens.TryRemove(id, out _); - - search.FileCount = soulseekSearch.FileCount; - search.LockedFileCount = soulseekSearch.LockedFileCount; - search.ResponseCount = soulseekSearch.ResponseCount; - search.State = soulseekSearch.State; - search.EndedAt = DateTime.UtcNow; - search.Responses = responses; - SaveSearchState(search); - - return search; - } - finally + Log.Error(ex, "Failed to persist search for {SearchQuery} ({Id})", query, id); + } + } + }); + + return search; + } + + /// <summary> + /// Deletes the specified ssearch. + /// </summary> + /// <param name="search">The search to delete.</param> + /// <returns>The operation context.</returns> + public async Task DeleteAsync(Search search) + { + if (search == default) { - CancellationTokens.TryRemove(id, out _); - Application.CollectGarbage(); + throw new ArgumentNullException(nameof(search)); } + + using var context = ContextFactory.CreateDbContext(); + context.Searches.Remove(search); + await context.SaveChangesAsync(); + + await SearchHub.BroadcastDeleteAsync(search); } /// <summary> @@ -197,35 +228,5 @@ namespace slskd.Search return false; } - - private void UpdateSearchState(Search search, SoulseekSearch soulseekSearch) - { - if (CancellationTokens.ContainsKey(search.Id)) - { - search.FileCount = soulseekSearch.FileCount; - search.LockedFileCount = soulseekSearch.LockedFileCount; - search.ResponseCount = soulseekSearch.ResponseCount; - search.State = soulseekSearch.State; - - SearchHub.BroadcastUpdateAsync(search); - SaveSearchState(search); - } - } - - private void UpdateSearchResponses(Search search, SoulseekSearch soulseekSearch, Soulseek.SearchResponse response) - { - if (CancellationTokens.ContainsKey(search.Id)) - { - SearchHub.BroadcastResponseAsync(search.Id, response); - UpdateSearchState(search, soulseekSearch); - } - } - - private void SaveSearchState(Search search) - { - var context = ContextFactory.CreateDbContext(); - context.Update(search); - context.SaveChanges(); - } } }
\ No newline at end of file |
