diff options
| author | JP Dillingham <jp@dillingham.me> | 2025-03-02 22:10:01 -0600 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2025-03-02 22:10:01 -0600 |
| commit | 07b0ea98eb2b5ef44b33754d7a3f7b098f6a8987 (patch) | |
| tree | 33a42d72316b7d312c25c44a938554af1430a058 /src/slskd/Search | |
| parent | a966dbd2e9d12b3bc6df63c9a3d58fbf074f2537 (diff) | |
| parent | be824b6b4af939f3a07752adc51405bf71e44ff2 (diff) | |
| download | slskd-07b0ea98eb2b5ef44b33754d7a3f7b098f6a8987.tar.gz | |
Merge branch 'master' into patch-1
Diffstat (limited to 'src/slskd/Search')
| -rw-r--r-- | src/slskd/Search/API/Controllers/SearchesController.cs | 9 | ||||
| -rw-r--r-- | src/slskd/Search/SearchService.cs | 127 |
2 files changed, 96 insertions, 40 deletions
diff --git a/src/slskd/Search/API/Controllers/SearchesController.cs b/src/slskd/Search/API/Controllers/SearchesController.cs index d6d96bbe..58e1fe37 100644 --- a/src/slskd/Search/API/Controllers/SearchesController.cs +++ b/src/slskd/Search/API/Controllers/SearchesController.cs @@ -24,6 +24,7 @@ namespace slskd.Search.API using Asp.Versioning; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; + using Serilog; using SearchQuery = Soulseek.SearchQuery; using SearchScope = Soulseek.SearchScope; @@ -50,6 +51,7 @@ namespace slskd.Search.API private ISearchService Searches { get; } private IOptionsSnapshot<Options> OptionsSnapshot { get; } + private ILogger Log { get; set; } = Serilog.Log.ForContext<SearchesController>(); /// <summary> /// Performs a search for the specified <paramref name="request"/>. @@ -83,12 +85,19 @@ namespace slskd.Search.API } catch (Exception ex) when (ex is ArgumentException || ex is Soulseek.DuplicateTokenException) { + Log.Error(ex, "Failed to execute search {Search}: {Message}", request, ex.Message); return BadRequest(ex.Message); } catch (InvalidOperationException ex) { + Log.Error(ex, "Failed to execute search {Search}: {Message}", request, ex.Message); return Conflict(ex.Message); } + catch (Exception ex) + { + Log.Error(ex, "Failed to execute search {Search}: {Message}", request, ex.Message); + return StatusCode(500, ex.Message); + } return Ok(search); } diff --git a/src/slskd/Search/SearchService.cs b/src/slskd/Search/SearchService.cs index 809647b2..b4864918 100644 --- a/src/slskd/Search/SearchService.cs +++ b/src/slskd/Search/SearchService.cs @@ -65,6 +65,15 @@ namespace slskd.Search Task<List<Search>> ListAsync(Expression<Func<Search, bool>> expression = null); /// <summary> + /// Updates the specified <paramref name="search"/>. + /// </summary> + /// <remark> + /// Round-trips the database; use accordingly. + /// </remark> + /// <param name="search">The search to update.</param> + void Update(Search search); + + /// <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> @@ -192,6 +201,17 @@ namespace slskd.Search } /// <summary> + /// Updates the specified <paramref name="search"/>. + /// </summary> + /// <param name="search">The search to update.</param> + public void Update(Search search) + { + using var context = ContextFactory.CreateDbContext(); + context.Update(search); + context.SaveChanges(); + } + + /// <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> @@ -208,6 +228,8 @@ namespace slskd.Search var rateLimiter = new RateLimiter(250); + // initialize the search record, save it to the database, and broadcast the creation + // we do this so the UI has some feedback to show to the user that we've gotten their request var search = new Search() { SearchText = query.SearchText, @@ -221,14 +243,11 @@ namespace slskd.Search context.Add(search); context.SaveChanges(); - List<SearchResponse> responses = new(); + await SearchHub.BroadcastCreateAsync(search); - void UpdateAndSaveChanges(Search search) - { - using var context = ContextFactory.CreateDbContext(); - context.Update(search); - context.SaveChanges(); - } + // initialize the list of responses that we'll use to accumulate them + // populated by the responseHandler we pass to SearchAsync + List<SearchResponse> responses = new(); options ??= new SearchOptions(); options = options.WithActions( @@ -236,7 +255,7 @@ namespace slskd.Search { search = search.WithSoulseekSearch(args.Search); SearchHub.BroadcastUpdateAsync(search); - UpdateAndSaveChanges(search); + Update(search); }, responseReceived: (args) => rateLimiter.Invoke(() => { @@ -250,50 +269,78 @@ namespace slskd.Search // 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); + Update(search); })); - var soulseekSearchTask = Client.SearchAsync( - query, - responseHandler: (response) => responses.Add(response), - scope, - token, - options, - cancellationToken: cancellationTokenSource.Token); - - _ = Task.Run(async () => + try { - try - { - var soulseekSearch = await soulseekSearchTask; - search = search.WithSoulseekSearch(soulseekSearch); - } - finally + // initiate the search. this can throw at invocation if there's a problem with + // the client state (e.g. disconnected) or a problem with the search (e.g. no terms) + var soulseekSearchTask = Client.SearchAsync( + query, + responseHandler: (response) => responses.Add(response), + scope, + token, + options, + cancellationToken: cancellationTokenSource.Token); + + // seach looks ok so far; let the rest of the logic run asynchronously + // on a background thread. this logic needs to clean up after itself and + // update the search record to accurately reflect the final state + _ = Task.Run(async () => { - 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, as we don't want to blast this - // data out over the SignalR socket - await SearchHub.BroadcastUpdateAsync(search with { Responses = [] }); + var soulseekSearch = await soulseekSearchTask; + search = search.WithSoulseekSearch(soulseekSearch); } catch (Exception ex) { - Log.Error(ex, "Failed to persist search for {SearchQuery} ({Id})", query, id); + Log.Error(ex, "Failed to execute search {Search}: {Message}", new { query, scope, options }, ex.Message); + search.State = SearchStates.Completed | SearchStates.Errored; } - } - }); + finally + { + rateLimiter.Dispose(); + CancellationTokens.TryRemove(id, out _); + + try + { + search.EndedAt = DateTime.UtcNow; + search.Responses = responses.Select(r => Response.FromSoulseekSearchResponse(r)); + + Update(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) + { + // record may be left 'hanging' and will need to be cleaned up at the next boot + Log.Error(ex, "Failed to persist search for {SearchQuery} ({Id})", query, id); + } + } + }); - await SearchHub.BroadcastCreateAsync(search); + await SearchHub.BroadcastUpdateAsync(search); + + return search; + } + catch (Exception ex) + { + // we'll end up here if the initial call throws for an ArgumentException, InvalidOperationException if + // the app isn't connected, and a few other straightforward issues that arise before even requesting the search + Log.Error(ex, "Failed to execute search {Search}: {Message}", new { query, scope, options }, ex.Message); - return search; + search.State = SearchStates.Completed | SearchStates.Errored; + search.EndedAt = search.StartedAt; + Update(search); + + await SearchHub.BroadcastUpdateAsync(search with { Responses = [] }); + + throw; + } } /// <summary> |
