diff --git a/AudioCuesheetEditor/Components/Record/AddTrack.razor b/AudioCuesheetEditor/Components/Record/AddTrack.razor index 7a118f8f..ce48a454 100644 --- a/AudioCuesheetEditor/Components/Record/AddTrack.razor +++ b/AudioCuesheetEditor/Components/Record/AddTrack.razor @@ -27,57 +27,55 @@ along with Foobar. If not, see - - @{ - MusicBrainzArtist? autocompleteArtist = new() + @{ + MusicBrainzArtist? autocompleteArtist = new() + { + Name = _currentRecordingTrack.Artist + }; + } + + + @if (autocompleteContext.Disambiguation != null) + { + @String.Format("{0} ({1})", autocompleteContext.Name, autocompleteContext.Disambiguation) + } + else + { + @autocompleteContext.Name + } + + + @{ + MusicBrainzTrack? autocompleteTrack = new() + { + Artist = _currentRecordingTrack.Artist, + Title = _currentRecordingTrack.Title + }; + } + + + @if (autocompleteContext.Disambiguation != null) { - Name = _currentRecordingTrack.Artist - }; - } - - - @if (autocompleteContext.Disambiguation != null) - { - @String.Format("{0} ({1})", autocompleteContext.Name, autocompleteContext.Disambiguation) - } - else - { - @autocompleteContext.Name - } - - - @{ - MusicBrainzTrack? autocompleteTrack = new() + @String.Format("{0} ({1})", autocompleteContext.Title, autocompleteContext.Disambiguation) + } + else { - Artist = _currentRecordingTrack.Artist, - Title = _currentRecordingTrack.Title - }; - } - - - @if (autocompleteContext.Disambiguation != null) - { - @String.Format("{0} ({1})", autocompleteContext.Title, autocompleteContext.Disambiguation) - } - else - { - @autocompleteContext.Title - } - - - - @_localizer["Add track"] - - - - - + @autocompleteContext.Title + } + + + + @_localizer["Add track"] + + + + diff --git a/AudioCuesheetEditor/Services/Provider/MusicBrainzDataProvider.cs b/AudioCuesheetEditor/Services/Provider/MusicBrainzDataProvider.cs index d1a2951c..2de77161 100644 --- a/AudioCuesheetEditor/Services/Provider/MusicBrainzDataProvider.cs +++ b/AudioCuesheetEditor/Services/Provider/MusicBrainzDataProvider.cs @@ -13,10 +13,12 @@ //You should have received a copy of the GNU General Public License //along with Foobar. If not, see //. +using System.Collections.Concurrent; +using System.Reflection; +using MetaBrainz.Common; using MetaBrainz.MusicBrainz; using MetaBrainz.MusicBrainz.Interfaces.Entities; using MetaBrainz.MusicBrainz.Interfaces.Searches; -using System.Reflection; namespace AudioCuesheetEditor.Services.Provider; @@ -34,97 +36,247 @@ public class MusicBrainzTrack public TimeSpan? Length { get; init; } public string? Disambiguation { get; init; } } -public partial class MusicBrainzDataProvider(ILogger logger) +public partial class MusicBrainzDataProvider : IDisposable { - readonly ILogger _logger = logger; + static string? _applicationVersion; + readonly record struct TitleSearchKey(string SearchString, string? Artist); + + const string _application = "AudioCuesheetEditor"; + const string _projectUrl = "https://github.com/NeoCoderMatrix86/AudioCuesheetEditor"; + const int _maxRequestAttempts = 3; + readonly TimeSpan _minimumTimeBetweenRequests = TimeSpan.FromMilliseconds(1100); + readonly ILogger _logger; + readonly SemaphoreSlim _requestGate = new(1, 1); + readonly Lock _lastRequestLock = new(); + DateTimeOffset _lastRequestStarted = DateTimeOffset.MinValue; + readonly ConcurrentDictionary>>> _artistSearchCache = new(); + readonly ConcurrentDictionary>>> _titleSearchCache = new(); + bool _disposedValue; + + public MusicBrainzDataProvider(ILogger logger) + { + _logger = logger; + var versionAttribute = Assembly.GetExecutingAssembly().GetCustomAttribute(); + if (versionAttribute != null) + { + _applicationVersion = versionAttribute.InformationalVersion; + } + } - public const string Application = "AudioCuesheetEditor"; - public const string ProjectUrl = "https://github.com/NeoCoderMatrix86/AudioCuesheetEditor"; + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } public async Task> SearchArtistAsync(string? searchString, CancellationToken token) { - List artistSearchResult = []; + if (string.IsNullOrWhiteSpace(searchString)) + { + return []; + } + var cacheKey = searchString.Trim(); + + var cachedSearch = _artistSearchCache.GetOrAdd( + cacheKey, + new Lazy>>(() => GetMusicBrainzArtistsAsync(cacheKey), LazyThreadSafetyMode.ExecutionAndPublication)); try { - if (string.IsNullOrEmpty(searchString) == false) - { - using var query = new Query(Application, ApplicationVersion, ProjectUrl); - var findArtistsResult = await query.FindArtistsAsync(searchString, simple: true, cancellationToken: token); - artistSearchResult = findArtistsResult.Results.ToList().ConvertAll(x => new MusicBrainzArtist() { Id = x.Item.Id, Name = x.Item.Name, Disambiguation = x.Item.Disambiguation }); - } + return await cachedSearch.Value.WaitAsync(token); + } + catch (OperationCanceledException) when (token.IsCancellationRequested) + { + throw; + } + catch (HttpError he) + { + _ = _artistSearchCache.TryRemove(cacheKey, out _); + LogHttpError(he, he.Message); + return []; } catch (HttpRequestException hre) { - LogErrorGettingResponseFromMusicBrainz(hre); + _ = _artistSearchCache.TryRemove(cacheKey, out _); + LogHttpRequestException(hre); + return []; } - return artistSearchResult.AsReadOnly(); } public async Task> SearchTitleAsync(string? searchString, string? artist, CancellationToken token) { - List titleSearchResult = []; + if (string.IsNullOrWhiteSpace(searchString)) + { + return []; + } + + var normalizedSearchString = searchString.Trim(); + var normalizedArtist = string.IsNullOrWhiteSpace(artist) ? null : artist.Trim(); + var cacheKey = new TitleSearchKey(normalizedSearchString, normalizedArtist); + + var cachedSearch = _titleSearchCache.GetOrAdd( + cacheKey, + new Lazy>>(() => GetMusicBrainzTracksAsync(normalizedSearchString, normalizedArtist), LazyThreadSafetyMode.ExecutionAndPublication)); + try { - if (string.IsNullOrEmpty(searchString) == false) + return await cachedSearch.Value.WaitAsync(token); + } + catch (OperationCanceledException) when (token.IsCancellationRequested) + { + throw; + } + catch (HttpError he) + { + _ = _titleSearchCache.TryRemove(cacheKey, out _); + LogHttpError(he, he.Message); + return []; + } + catch (HttpRequestException hre) + { + _ = _titleSearchCache.TryRemove(cacheKey, out _); + LogHttpRequestException(hre); + return []; + } + } + + protected virtual void Dispose(bool disposing) + { + if (!_disposedValue) + { + if (disposing) + { + _requestGate.Dispose(); + } + + _disposedValue = true; + } + } + + async Task WaitForRequestSlotAsync() + { + await _requestGate.WaitAsync(); + + TimeSpan delay; + + lock (_lastRequestLock) + { + delay = _lastRequestStarted + _minimumTimeBetweenRequests - DateTimeOffset.UtcNow; + + if (delay < TimeSpan.Zero) { - using var query = new Query(Application, ApplicationVersion, ProjectUrl); - ISearchResults> findRecordingsResult; + delay = TimeSpan.Zero; + } + } + + if (delay > TimeSpan.Zero) + { + await Task.Delay(delay); + } + + lock (_lastRequestLock) + { + _lastRequestStarted = DateTimeOffset.UtcNow; + } + } + + async Task> GetMusicBrainzArtistsAsync(string searchString) + { + for (var attempt = 1; attempt <= _maxRequestAttempts; attempt++) + { + await WaitForRequestSlotAsync(); + + try + { + using var query = new Query(_application, _applicationVersion, _projectUrl); + var result = await query.FindArtistsAsync(searchString, simple: true); + + return [.. result.Results + .Select(x => new MusicBrainzArtist + { + Id = x.Item.Id, + Name = x.Item.Name, + Disambiguation = x.Item.Disambiguation + })]; + } + catch (HttpError he) when (IsMusicBrainzBusy(he) && attempt < _maxRequestAttempts) + { + var delay = TimeSpan.FromSeconds(Math.Pow(2, attempt - 1)); + await Task.Delay(delay); + } + finally + { + _ = _requestGate.Release(); + } + } + return []; + } + + async Task> GetMusicBrainzTracksAsync(string searchString, string? artist) + { + for (var attempt = 1; attempt <= _maxRequestAttempts; attempt++) + { + await WaitForRequestSlotAsync(); + try + { + using var query = new Query(_application, _applicationVersion, _projectUrl); + ISearchResults> result; + if (string.IsNullOrEmpty(artist)) { - findRecordingsResult = await query.FindRecordingsAsync(searchString, simple: true, cancellationToken: token); + result = await query.FindRecordingsAsync(searchString, simple: true); } else { - findRecordingsResult = await query.FindRecordingsAsync($"{searchString} AND artistname:{artist}", cancellationToken: token); + result = await query.FindRecordingsAsync($"{searchString} AND artistname:{artist}"); } - foreach (var result in findRecordingsResult.Results) + + var tracks = new List(); + foreach (var recording in result.Results) { var artistString = string.Empty; - if (result.Item.ArtistCredit != null) + if (recording.Item.ArtistCredit != null) { - foreach (var artistCredit in result.Item.ArtistCredit) + foreach (var artistCredit in recording.Item.ArtistCredit) { artistString += artistCredit.Name; - if (string.IsNullOrEmpty(artistCredit.JoinPhrase) == false) + if (!string.IsNullOrEmpty(artistCredit.JoinPhrase)) { artistString += artistCredit.JoinPhrase; } } } - titleSearchResult.Add(new MusicBrainzTrack() + + tracks.Add(new MusicBrainzTrack { - Id = result.Item.Id, + Id = recording.Item.Id, Artist = artistString, - Title = result.Item.Title, - Length = result.Item.Length, - Disambiguation = result.Item.Disambiguation + Title = recording.Item.Title, + Length = recording.Item.Length, + Disambiguation = recording.Item.Disambiguation }); } - } - } - catch (HttpRequestException hre) - { - LogErrorGettingResponseFromMusicBrainz(hre); - } - return titleSearchResult.AsReadOnly(); - } - string? ApplicationVersion - { - get - { - if (field == null) + return tracks.AsReadOnly(); + } + catch (HttpError he) when (IsMusicBrainzBusy(he) && attempt < _maxRequestAttempts) { - var versionAttribute = Assembly.GetExecutingAssembly().GetCustomAttribute(); - if (versionAttribute != null) - { - field = versionAttribute.InformationalVersion; - } + var delay = TimeSpan.FromSeconds(Math.Pow(2, attempt - 1)); + await Task.Delay(delay); + } + finally + { + _ = _requestGate.Release(); } - return field; } + + return []; } - [LoggerMessage(Level = LogLevel.Error, Message = "Error getting response from MusicBrainz")] - partial void LogErrorGettingResponseFromMusicBrainz(HttpRequestException hre); + static bool IsMusicBrainzBusy(HttpError error) => error.Message.StartsWith("The MusicBrainz web server is currently busy. Please try again later.", StringComparison.InvariantCultureIgnoreCase); + + [LoggerMessage(Level = LogLevel.Error, Message = "General error getting response from MusicBrainz")] + partial void LogHttpRequestException(HttpRequestException hre); + + [LoggerMessage(Level = LogLevel.Error, Message = "HttpError caught: {exceptionMessage}")] + partial void LogHttpError(HttpError he, string exceptionMessage); }