// // 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/. // using Microsoft.Extensions.Options; namespace slskd.Search { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR; using Microsoft.EntityFrameworkCore; using Serilog; using slskd.Search.API; using Soulseek; using SearchOptions = Soulseek.SearchOptions; using SearchQuery = Soulseek.SearchQuery; using SearchScope = Soulseek.SearchScope; using SearchStates = Soulseek.SearchStates; /// /// Handles the lifecycle and persistence of searches. /// public class SearchService : ISearchService { /// /// Initializes a new instance of the class. /// /// /// /// /// The database context to use. public SearchService( IHubContext searchHub, IOptionsMonitor optionsMonitor, ISoulseekClient soulseekClient, IDbContextFactory contextFactory) { SearchHub = searchHub; OptionsMonitor = optionsMonitor; Client = soulseekClient; ContextFactory = contextFactory; } private ConcurrentDictionary CancellationTokens { get; } = new ConcurrentDictionary(); private ISoulseekClient Client { get; } private IDbContextFactory ContextFactory { get; } private ILogger Log { get; set; } = Serilog.Log.ForContext(); private IOptionsMonitor OptionsMonitor { get; } private IHubContext SearchHub { get; set; } /// /// Deletes the specified ssearch. /// /// The search to delete. /// The operation context. public Task DeleteAsync(Search search) { if (search == default) { throw new ArgumentNullException(nameof(search)); } return DoDeleteAsync(search); async Task DoDeleteAsync(Search search) { using var context = ContextFactory.CreateDbContext(); context.Searches.Remove(search); context.SaveChanges(); await SearchHub.BroadcastDeleteAsync(search); } } /// /// Finds a single search matching the specified . /// /// The expression to use to match searches. /// A value indicating whether to include search responses in the result. /// The found search, or default if not found. /// Thrown when an expression is not supplied. public Task FindAsync(Expression> expression, bool includeResponses = false) { if (expression == default) { throw new ArgumentException("An expression must be supplied.", nameof(expression)); } using var context = ContextFactory.CreateDbContext(); var selector = context.Searches .AsNoTracking() .Where(expression); if (!includeResponses) { selector = selector.WithoutResponses(); } return selector.FirstOrDefaultAsync(); } /// /// Returns a list of all completed and in-progress searches, with responses omitted, matching the optional . /// /// An optional expression used to match searches. /// The list of searches matching the specified expression, or all searches if no expression is specified. public Task> ListAsync(Expression> expression = null) { expression ??= s => true; using var context = ContextFactory.CreateDbContext(); return context.Searches .AsNoTracking() .Where(expression) .WithoutResponses() .ToListAsync(); } /// /// Performs a search for the specified and . /// /// A unique identifier for the search. /// The search query. /// The search scope. /// Search options. /// The completed search. public async Task StartAsync(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() { SearchText = query.SearchText, Token = token, Id = id, State = SearchStates.Requested, StartedAt = DateTime.UtcNow, }; using var context = ContextFactory.CreateDbContext(); context.Add(search); context.SaveChanges(); List responses = new(); void UpdateAndSaveChanges(Search search) { using var context = ContextFactory.CreateDbContext(); context.Update(search); context.SaveChanges(); } options ??= new SearchOptions(); options = options.WithActions( stateChanged: (args) => { search = search.WithSoulseekSearch(args.Search); SearchHub.BroadcastUpdateAsync(search); UpdateAndSaveChanges(search); }, responseReceived: (args) => rateLimiter.Invoke(() => { // note: this is rate limited, but has the potential to update the database every 250ms (or whatever the // interval is set to) for the duration of the search. any issues with disk i/o or performance while searches // are running should investigate this as a cause search.ResponseCount = args.Search.ResponseCount; search.FileCount = args.Search.FileCount; search.LockedFileCount = args.Search.LockedFileCount; SearchHub.BroadcastUpdateAsync(search); UpdateAndSaveChanges(search); })); var soulseekSearchTask = Client.SearchAsync( query, responseHandler: (response) => responses.Add(response), scope, token, options, cancellationToken: cancellationTokenSource.Token); _ = Task.Run(async () => { try { var soulseekSearch = await soulseekSearchTask; search = search.WithSoulseekSearch(soulseekSearch); } finally { rateLimiter.Dispose(); CancellationTokens.TryRemove(id, out _); try { search.EndedAt = DateTime.UtcNow; search.Responses = responses.Select(r => Response.FromSoulseekSearchResponse(r)); UpdateAndSaveChanges(search); // zero responses before broadcasting search.Responses = Enumerable.Empty(); await SearchHub.BroadcastUpdateAsync(search); } catch (Exception ex) { Log.Error(ex, "Failed to persist search for {SearchQuery} ({Id})", query, id); } } }); await SearchHub.BroadcastCreateAsync(search); return search; } /// /// Cancels the search matching the specified , if it is in progress. /// /// The unique identifier for the search. /// A value indicating whether the search was sucessfully cancelled. public bool TryCancel(Guid id) { if (CancellationTokens.TryGetValue(id, out var cts)) { cts.Cancel(); return true; } return false; } } }