diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Application.cs | 22 | ||||
| -rw-r--r-- | src/slskd/Core/Options.cs | 6 | ||||
| -rw-r--r-- | src/slskd/Program.cs | 1 | ||||
| -rw-r--r-- | src/slskd/Search/API/Controllers/SearchesController.cs | 2 | ||||
| -rw-r--r-- | src/slskd/Search/API/Hubs/SearchHub.cs | 29 | ||||
| -rw-r--r-- | src/slskd/Search/ISearchService.cs | 71 | ||||
| -rw-r--r-- | src/slskd/Search/SearchService.cs | 98 | ||||
| -rw-r--r-- | src/slskd/Search/Types/Search.cs | 2 | ||||
| -rw-r--r-- | src/slskd/Transfers/Uploads/UploadService.cs | 10 |
9 files changed, 158 insertions, 83 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index b0372422..05f62902 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -96,6 +96,7 @@ namespace slskd IUserService userService, IMessagingService messagingService, IShareService shareService, + ISearchService searchService, IPushbulletService pushbulletService, IRelayService relayService, EventService eventService, @@ -146,6 +147,8 @@ namespace slskd Shares = shareService; Shares.StateMonitor.OnChange(state => ShareState_OnChange(state)); + Search = searchService; + Events = eventService; Transfers = transferService; @@ -227,6 +230,7 @@ namespace slskd private IHubContext<LogsHub> LogHub { get; set; } private IUserService Users { get; set; } private IShareService Shares { get; set; } + private ISearchService Search { get; set; } private EventService Events { get; } private IRelayService Relay { get; set; } private IMemoryCache Cache { get; set; } = new MemoryCache(new MemoryCacheOptions()); @@ -1003,6 +1007,7 @@ namespace slskd private void Clock_EveryFiveMinutes(object sender, ClockEventArgs e) { + _ = Task.Run(() => PruneSearches()); _ = Task.Run(() => PruneTransfers()); } @@ -1142,6 +1147,23 @@ namespace slskd } } + private async Task PruneSearches() + { + var age = OptionsMonitor.CurrentValue.Retention.Search; + + if (age.HasValue) + { + try + { + var pruned = await Search.PruneAsync(age.Value); + } + catch + { + Log.Error("Encountered one or more errors while pruning searches"); + } + } + } + private void Client_ExcludedSearchPhrasesReceived(object sender, IReadOnlyCollection<string> e) { Log.Debug("Excluded search phrases: {Phrases}", string.Join(", ", e)); diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index e5f16b1e..a7fb26c4 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1312,6 +1312,12 @@ namespace slskd public class RetentionOptions { /// <summary> + /// Gets the time to retain searches, in minutes. + /// </summary> + [Range(5, maximum: int.MaxValue)] + public int? Search { get; init; } = null; + + /// <summary> /// Gets transfer retention options. /// </summary> [Validate] diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index b302cc8c..f2c61b14 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -1024,6 +1024,7 @@ namespace slskd .MinimumLevel.Override("System.Net.Http.HttpClient", OptionsAtStartup.Debug ? LogEventLevel.Warning : LogEventLevel.Fatal) .MinimumLevel.Override("slskd.Authentication.PassthroughAuthenticationHandler", LogEventLevel.Warning) .MinimumLevel.Override("slskd.Authentication.ApiKeyAuthenticationHandler", LogEventLevel.Warning) + .MinimumLevel.Override("Microsoft.EntityFrameworkCore.Database.Command", LogEventLevel.Warning) // bump this down to Information to show SQL .Enrich.WithProperty("InstanceName", OptionsAtStartup.InstanceName) .Enrich.WithProperty("InvocationId", InvocationId) .Enrich.WithProperty("ProcessId", ProcessId) diff --git a/src/slskd/Search/API/Controllers/SearchesController.cs b/src/slskd/Search/API/Controllers/SearchesController.cs index 56c5f533..d6d96bbe 100644 --- a/src/slskd/Search/API/Controllers/SearchesController.cs +++ b/src/slskd/Search/API/Controllers/SearchesController.cs @@ -210,7 +210,7 @@ namespace slskd.Search.API return Forbid(); } - var search = await Searches.FindAsync(search => search.Id == id, includeResponses: true); + var search = await Searches.FindAsync(search => search.Id == id, includeResponses: false); if (search == default) { diff --git a/src/slskd/Search/API/Hubs/SearchHub.cs b/src/slskd/Search/API/Hubs/SearchHub.cs index b1fbf725..e1cfb4b5 100644 --- a/src/slskd/Search/API/Hubs/SearchHub.cs +++ b/src/slskd/Search/API/Hubs/SearchHub.cs @@ -39,16 +39,19 @@ namespace slskd.Search.API /// <summary> /// Broadcast an update for a search. /// </summary> + /// <remarks> + /// Responses are removed prior to sending. + /// </remarks> /// <param name="hub">The hub.</param> /// <param name="search">The search to broadcast.</param> /// <returns>The operation context.</returns> public static Task BroadcastUpdateAsync(this IHubContext<SearchHub> hub, Search search) { - return hub.Clients.All.SendAsync(SearchHubMethods.Update, search); + return hub.Clients.All.SendAsync(SearchHubMethods.Update, search with { Responses = null }); } /// <summary> - /// Broadcast the present application options. + /// Broadcast a newly received search response. /// </summary> /// <param name="hub">The hub.</param> /// <param name="searchId">The ID of the search associated with the response.</param> @@ -59,14 +62,32 @@ namespace slskd.Search.API return hub.Clients.All.SendAsync(SearchHubMethods.Response, new { searchId, response }); } + /// <summary> + /// Broadcast the creation of a new search. + /// </summary> + /// <remarks> + /// Responses are removed prior to sending. + /// </remarks> + /// <param name="hub">The hub.</param> + /// <param name="search">The search to broadcast.</param> + /// <returns>The operation context.</returns> public static Task BroadcastCreateAsync(this IHubContext<SearchHub> hub, Search search) { - return hub.Clients.All.SendAsync(SearchHubMethods.Create, search); + return hub.Clients.All.SendAsync(SearchHubMethods.Create, search with { Responses = null }); } + /// <summary> + /// Broadcast the deletion of a search. + /// </summary> + /// <remarks> + /// Responses are removed prior to sending. + /// </remarks> + /// <param name="hub">The hub.</param> + /// <param name="search">The search to broadcast.</param> + /// <returns>The operation context.</returns> public static Task BroadcastDeleteAsync(this IHubContext<SearchHub> hub, Search search) { - return hub.Clients.All.SendAsync(SearchHubMethods.Delete, search); + return hub.Clients.All.SendAsync(SearchHubMethods.Delete, search with { Responses = null }); } } diff --git a/src/slskd/Search/ISearchService.cs b/src/slskd/Search/ISearchService.cs deleted file mode 100644 index 097e23de..00000000 --- a/src/slskd/Search/ISearchService.cs +++ /dev/null @@ -1,71 +0,0 @@ -// <copyright file="ISearchService.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.Search -{ - using System; - using System.Collections.Generic; - using System.Linq.Expressions; - using System.Threading.Tasks; - using Soulseek; - - /// <summary> - /// Handles the lifecycle and persistence of searches. - /// </summary> - public interface ISearchService - { - /// <summary> - /// Deletes the specified search. - /// </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> - /// <param name="includeResponses">A value indicating whether to include search responses in the result.</param> - /// <returns>The found search, or default if not found.</returns> - /// <exception cref="ArgumentException">Thrown when an expression is not supplied.</exception> - Task<Search> FindAsync(Expression<Func<Search, bool>> expression, bool includeResponses = false); - - /// <summary> - /// Returns a list of all completed and in-progress searches, with responses omitted, matching the optional <paramref name="expression"/>. - /// </summary> - /// <param name="expression">An optional expression used to match searches.</param> - /// <returns>The list of searches matching the specified expression, or all searches if no expression is specified.</returns> - Task<List<Search>> ListAsync(Expression<Func<Search, bool>> expression = null); - - /// <summary> - /// Performs a search for the specified <paramref name="query"/> and <paramref name="scope"/>. - /// </summary> - /// <param name="id">A unique identifier for the search.</param> - /// <param name="query">The search query.</param> - /// <param name="scope">The search scope.</param> - /// <param name="options">Search options.</param> - /// <returns>The completed search.</returns> - Task<Search> StartAsync(Guid id, SearchQuery query, SearchScope scope, SearchOptions options = null); - - /// <summary> - /// Cancels the search matching the specified <paramref name="id"/>, if it is in progress. - /// </summary> - /// <param name="id">The unique identifier for the search.</param> - /// <returns>A value indicating whether the search was successfully cancelled.</returns> - bool TryCancel(Guid id); - } -}
\ No newline at end of file diff --git a/src/slskd/Search/SearchService.cs b/src/slskd/Search/SearchService.cs index 3d2e2750..809647b2 100644 --- a/src/slskd/Search/SearchService.cs +++ b/src/slskd/Search/SearchService.cs @@ -39,6 +39,59 @@ namespace slskd.Search /// <summary> /// Handles the lifecycle and persistence of searches. /// </summary> + public interface ISearchService + { + /// <summary> + /// Deletes the specified search. + /// </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> + /// <param name="includeResponses">A value indicating whether to include search responses in the result.</param> + /// <returns>The found search, or default if not found.</returns> + /// <exception cref="ArgumentException">Thrown when an expression is not supplied.</exception> + Task<Search> FindAsync(Expression<Func<Search, bool>> expression, bool includeResponses = false); + + /// <summary> + /// Returns a list of all completed and in-progress searches, with responses omitted, matching the optional <paramref name="expression"/>. + /// </summary> + /// <param name="expression">An optional expression used to match searches.</param> + /// <returns>The list of searches matching the specified expression, or all searches if no expression is specified.</returns> + Task<List<Search>> ListAsync(Expression<Func<Search, bool>> expression = null); + + /// <summary> + /// Performs a search for the specified <paramref name="query"/> and <paramref name="scope"/>. + /// </summary> + /// <param name="id">A unique identifier for the search.</param> + /// <param name="query">The search query.</param> + /// <param name="scope">The search scope.</param> + /// <param name="options">Search options.</param> + /// <returns>The completed search.</returns> + Task<Search> StartAsync(Guid id, SearchQuery query, SearchScope scope, SearchOptions options = null); + + /// <summary> + /// Cancels the search matching the specified <paramref name="id"/>, if it is in progress. + /// </summary> + /// <param name="id">The unique identifier for the search.</param> + /// <returns>A value indicating whether the search was successfully cancelled.</returns> + bool TryCancel(Guid id); + + /// <summary> + /// Removes <see cref="SearchStates.Completed"/> searches older than the specified <paramref name="age"/>. + /// </summary> + /// <param name="age">The age after which records are eligible for pruning, in minutes.</param> + /// <returns>The number of pruned records.</returns> + Task<int> PruneAsync(int age); + } + + /// <summary> + /// Handles the lifecycle and persistence of searches. + /// </summary> public class SearchService : ISearchService { /// <summary> @@ -194,6 +247,8 @@ namespace slskd.Search search.FileCount = args.Search.FileCount; search.LockedFileCount = args.Search.LockedFileCount; + // note that we're not actually doing anything with the response here, that's happening in the + // response handler. we're only updating counts here. SearchHub.BroadcastUpdateAsync(search); UpdateAndSaveChanges(search); })); @@ -225,9 +280,9 @@ namespace slskd.Search UpdateAndSaveChanges(search); - // zero responses before broadcasting - search.Responses = Enumerable.Empty<Response>(); - await SearchHub.BroadcastUpdateAsync(search); + // zero responses before broadcasting, as we don't want to blast this + // data out over the SignalR socket + await SearchHub.BroadcastUpdateAsync(search with { Responses = [] }); } catch (Exception ex) { @@ -256,5 +311,42 @@ namespace slskd.Search return false; } + + /// <summary> + /// Removes <see cref="SearchStates.Completed"/> searches older than the specified <paramref name="age"/>. + /// </summary> + /// <param name="age">The age after which searches are eligible for pruning, in minutes.</param> + /// <returns>The number of pruned records.</returns> + public async Task<int> PruneAsync(int age) + { + try + { + using var context = ContextFactory.CreateDbContext(); + + var cutoffDateTime = DateTime.UtcNow.AddMinutes(-age); + + // unlike other pruning operations, we don't care about state, since there's a 60 minute minimum + // and searches are guaranteed to be at least 60 minutes old by the time they can be pruned, they will + // be completed unless someone applied some rather dumb settings + var expired = context.Searches + .Where(s => s.EndedAt.HasValue && s.EndedAt.Value < cutoffDateTime) + .WithoutResponses() + .ToList(); + + // defer the deletion to DeleteAsync() so that SignalR broadcasting works properly and the UI + // is updated in real time + foreach (var search in expired) + { + await DeleteAsync(search); + } + + return expired.Count; + } + catch (Exception ex) + { + Log.Error(ex, "Failed to prune searches: {Message}", ex.Message); + throw; + } + } } }
\ No newline at end of file diff --git a/src/slskd/Search/Types/Search.cs b/src/slskd/Search/Types/Search.cs index 52f97075..577faf14 100644 --- a/src/slskd/Search/Types/Search.cs +++ b/src/slskd/Search/Types/Search.cs @@ -25,7 +25,7 @@ namespace slskd.Search using System.Text.Json.Serialization; using Soulseek; - public class Search + public record Search { public DateTime? EndedAt { get; set; } public int FileCount { get; set; } diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index aeb2f63c..fa9a3359 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -94,7 +94,7 @@ namespace slskd.Transfers.Uploads /// <summary> /// Removes <see cref="TransferStates.Completed"/> uploads older than the specified <paramref name="age"/>. /// </summary> - /// <param name="age">The age after which uploads are eligible for pruning, in hours.</param> + /// <param name="age">The age after which uploads are eligible for pruning, in minutes.</param> /// <param name="state">An optional, additional state by which uploads are filtered for pruning.</param> /// <returns>The number of pruned uploads.</returns> int Prune(int age, TransferStates state = TransferStates.Completed); @@ -533,7 +533,7 @@ namespace slskd.Transfers.Uploads /// <summary> /// Removes <see cref="TransferStates.Completed"/> uploads older than the specified <paramref name="age"/>. /// </summary> - /// <param name="age">The age after which uploads are eligible for pruning, in hours.</param> + /// <param name="age">The age after which uploads are eligible for pruning, in minutes.</param> /// <param name="state">An optional, additional state by which uploads are filtered for pruning.</param> /// <returns>The number of pruned uploads.</returns> public int Prune(int age, TransferStates state = TransferStates.Completed) @@ -553,7 +553,11 @@ namespace slskd.Transfers.Uploads .Where(t => t.Direction == TransferDirection.Upload) .Where(t => !t.Removed) .Where(t => t.EndedAt.HasValue && t.EndedAt.Value < cutoffDateTime) - .Where(t => t.State == state) // https://github.com/dotnet/efcore/issues/20094 + + // note: don't try HasFlag() here: https://github.com/dotnet/efcore/issues/20094 + // this won't work because the state is stored as a comma separated string (which we've done deliberately) + // and EF won't do the necessary work to generate the required SQL + .Where(t => t.State == state) .ToList(); foreach (var tx in expired) |
