From ef5371276a7293d464fd058dcfa903072fae67e8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 28 May 2021 15:02:22 -0500 Subject: polish SearchService --- src/slskd/Core/Search/ISearchService.cs | 31 ---- src/slskd/Core/Search/SearchService.cs | 137 --------------- src/slskd/Core/Search/Services/ISearchService.cs | 67 ++++++++ src/slskd/Core/Search/Services/SearchService.cs | 203 +++++++++++++++++++++++ 4 files changed, 270 insertions(+), 168 deletions(-) delete mode 100644 src/slskd/Core/Search/ISearchService.cs delete mode 100644 src/slskd/Core/Search/SearchService.cs create mode 100644 src/slskd/Core/Search/Services/ISearchService.cs create mode 100644 src/slskd/Core/Search/Services/SearchService.cs (limited to 'src') diff --git a/src/slskd/Core/Search/ISearchService.cs b/src/slskd/Core/Search/ISearchService.cs deleted file mode 100644 index 44d3edb9..00000000 --- a/src/slskd/Core/Search/ISearchService.cs +++ /dev/null @@ -1,31 +0,0 @@ -// -// 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/. -// - -namespace slskd.Search -{ - using System; - using System.Linq.Expressions; - using System.Threading.Tasks; - using Soulseek; - - public interface ISearchService - { - Task SearchAsync(Guid id, SearchQuery query, SearchScope scope, SearchOptions options = null); - bool TryCancel(Guid id); - Task FindAsync(Expression> expression, bool includeResponses = false); - } -} diff --git a/src/slskd/Core/Search/SearchService.cs b/src/slskd/Core/Search/SearchService.cs deleted file mode 100644 index 0fd4d6d5..00000000 --- a/src/slskd/Core/Search/SearchService.cs +++ /dev/null @@ -1,137 +0,0 @@ -// -// 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/. -// - -namespace slskd.Search -{ - using System; - using System.Collections.Concurrent; - using System.Collections.Generic; - using System.Linq.Expressions; - using System.Threading; - using System.Threading.Tasks; - using Microsoft.EntityFrameworkCore; - using Microsoft.Extensions.Logging; - using Soulseek; - - public class SearchService : ISearchService - { - public SearchService( - IDbContextFactory contextFactory, - ILogger log, - ISoulseekClient client) - { - ContextFactory = contextFactory; - Log = log; - Client = client; - } - - private IDbContextFactory ContextFactory { get; } - private ILogger Log { get; set; } - private ISoulseekClient Client { get; } - - private ConcurrentDictionary CancellationTokens { get; } - = new ConcurrentDictionary(); - - public async Task SearchAsync(Guid id, SearchQuery query, SearchScope scope, SearchOptions options = null) - { - var token = Client.GetNextToken(); - var cancellationTokenSource = new CancellationTokenSource(); - - var search = new Search() - { - SearchText = query.SearchText, - Token = token, - Id = id, - State = SearchStates.Requested, - StartedAt = DateTime.UtcNow, - }; - - options ??= new SearchOptions(); - options = options.WithActions(stateChanged: (args) => UpdateState(search, args.Search), (args) => UpdateState(search, args.Search)); - - using var context = ContextFactory.CreateDbContext(); - - context.Add(search); - await context.SaveChangesAsync(); - - CancellationTokens.TryAdd(id, cancellationTokenSource); - var responses = new List(); - - var soulseekSearch = await Client.SearchAsync( - query, - responseReceived: (response) => - { - responses.Add(Response.FromSoulseekSearchResponse(response)); - }, - scope, - token, - options, - cancellationToken: cancellationTokenSource.Token); - - search.FileCount = soulseekSearch.FileCount; - search.LockedFileCount = soulseekSearch.LockedFileCount; - search.ResponseCount = soulseekSearch.ResponseCount; - search.State = soulseekSearch.State; - search.Responses = responses; - - return search; - } - - public bool TryCancel(Guid id) - { - if (CancellationTokens.TryGetValue(id, out var cts)) - { - cts.Cancel(); - return true; - } - - return false; - } - - public async Task FindAsync(Expression> expression, bool includeResponses = true) - { - using var context = ContextFactory.CreateDbContext(); - var search = await context - .Searches - .FirstOrDefaultAsync(expression); - - if (!includeResponses) - { - - } - return search; - } - - private void UpdateState(Search search, Soulseek.Search soulseekSearch) - { - _ = Task.Run(async () => - { - search.FileCount = soulseekSearch.FileCount; - search.LockedFileCount = soulseekSearch.LockedFileCount; - search.ResponseCount = soulseekSearch.ResponseCount; - search.State = soulseekSearch.State; - - var context = ContextFactory.CreateDbContext(); - - context.Update(search); - await context.SaveChangesAsync(); - }).ContinueWith(task => - Log.LogError(task.Exception, "Failed to update state of {SearchId}", search.Id), - TaskContinuationOptions.OnlyOnFaulted); - } - } -} diff --git a/src/slskd/Core/Search/Services/ISearchService.cs b/src/slskd/Core/Search/Services/ISearchService.cs new file mode 100644 index 00000000..f56f2ab3 --- /dev/null +++ b/src/slskd/Core/Search/Services/ISearchService.cs @@ -0,0 +1,67 @@ +// +// 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/. +// + +namespace slskd.Search +{ + using System; + using System.Collections.Generic; + using System.Linq.Expressions; + using System.Threading.Tasks; + using SearchOptions = Soulseek.SearchOptions; + using SearchQuery = Soulseek.SearchQuery; + using SearchScope = Soulseek.SearchScope; + + /// + /// Handles the lifecycle and persistence of searches. + /// + public interface ISearchService + { + /// + /// Performs a search for the specified and . + /// + /// A unique identifier for the search. + /// The search query. + /// The search scope. + /// Search options. + /// A value indicating whether to include search responses in the result. + /// The completed search. + Task CreateAsync(Guid id, SearchQuery query, SearchScope scope, SearchOptions options = null, bool includeResponses = true); + + /// + /// 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 an expression is not supplied. + Task FindAsync(Expression> expression, bool includeResponses = false); + + /// + /// Returns a list of all completed and in-progress searches, with responses omitted. + /// + /// An optional expression used to match searches. + /// The list of searches matching the specified expression. + Task> ListAsync(Expression> expression = null); + + /// + /// 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. + bool TryCancel(Guid id); + } +} \ No newline at end of file diff --git a/src/slskd/Core/Search/Services/SearchService.cs b/src/slskd/Core/Search/Services/SearchService.cs new file mode 100644 index 00000000..7b6f0f2b --- /dev/null +++ b/src/slskd/Core/Search/Services/SearchService.cs @@ -0,0 +1,203 @@ +// +// 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/. +// + +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.EntityFrameworkCore; + using Microsoft.Extensions.Logging; + using ISoulseekClient = Soulseek.ISoulseekClient; + using SearchOptions = Soulseek.SearchOptions; + using SearchQuery = Soulseek.SearchQuery; + using SearchScope = Soulseek.SearchScope; + using SearchStates = Soulseek.SearchStates; + using SoulseekSearch = Soulseek.Search; + + /// + /// Handles the lifecycle and persistence of searches. + /// + public class SearchService : ISearchService + { + /// + /// Initializes a new instance of the class. + /// + /// The client instance to use. + /// The database context to use. + /// The logger. + public SearchService( + ISoulseekClient client, + IDbContextFactory contextFactory, + ILogger log) + { + Client = client; + ContextFactory = contextFactory; + Log = log; + } + + private ConcurrentDictionary CancellationTokens { get; } + = new ConcurrentDictionary(); + + private ISoulseekClient Client { get; } + private IDbContextFactory ContextFactory { get; } + private ILogger Log { get; set; } + + /// + /// Performs a search for the specified and . + /// + /// A unique identifier for the search. + /// The search query. + /// The search scope. + /// Search options. + /// A value indicating whether to include search responses in the result. + /// The completed search. + public async Task CreateAsync(Guid id, SearchQuery query, SearchScope scope, SearchOptions options = null, bool includeResponses = true) + { + var token = Client.GetNextToken(); + var cancellationTokenSource = new CancellationTokenSource(); + + var search = new Search() + { + SearchText = query.SearchText, + Token = token, + Id = id, + State = SearchStates.Requested, + StartedAt = DateTime.UtcNow, + }; + + options ??= new SearchOptions(); + options = options.WithActions( + stateChanged: (args) => UpdateSearchState(search, args.Search), + responseReceived: (args) => UpdateSearchState(search, args.Search)); + + try + { + using var context = ContextFactory.CreateDbContext(); + + context.Add(search); + await context.SaveChangesAsync(); + + CancellationTokens.TryAdd(id, cancellationTokenSource); + var responses = new List(); + + var soulseekSearch = await Client.SearchAsync( + query, + responseReceived: (response) => + { + responses.Add(Response.FromSoulseekSearchResponse(response)); + }, + scope, + token, + options, + cancellationToken: cancellationTokenSource.Token); + + search.FileCount = soulseekSearch.FileCount; + search.LockedFileCount = soulseekSearch.LockedFileCount; + search.ResponseCount = soulseekSearch.ResponseCount; + search.State = soulseekSearch.State; + + if (includeResponses) + { + search.Responses = responses; + } + + return search; + } + finally + { + CancellationTokens.TryRemove(id, out _); + } + } + + /// + /// 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 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.Where(expression); + + if (!includeResponses) + { + selector = selector.WithoutResponses(); + } + + return selector.FirstOrDefaultAsync(); + } + + /// + /// Returns a list of all completed and in-progress searches, with responses omitted. + /// + /// An optional expression used to match searches. + /// The list of searches matching the specified expression. + public Task> ListAsync(Expression> expression = null) + { + expression ??= s => true; + using var context = ContextFactory.CreateDbContext(); + return context.Searches.Where(expression).WithoutResponses().ToListAsync(); + } + + /// + /// 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; + } + + private void UpdateSearchState(Search search, SoulseekSearch soulseekSearch) + { + _ = Task.Run(async () => + { + search.FileCount = soulseekSearch.FileCount; + search.LockedFileCount = soulseekSearch.LockedFileCount; + search.ResponseCount = soulseekSearch.ResponseCount; + search.State = soulseekSearch.State; + + var context = ContextFactory.CreateDbContext(); + + context.Update(search); + await context.SaveChangesAsync(); + }).ContinueWith(task => + Log.LogError(task.Exception, "Failed to update state of {SearchId}", search.Id), + TaskContinuationOptions.OnlyOnFaulted); + } + } +} \ No newline at end of file -- cgit v1.2.3