#region ========================================================================= USING ===================================================================================== using Nemera.Plugins.Contracts.Common.Http; using Nemera.Plugins.MusicBrainz.Common.Models.Contracts.Responses; using Nemera.Plugins.MusicBrainz.Common.Models.DTO.Settings; using Nemera.Plugins.MusicBrainz.Core.Settings; using System; using System.Collections.Generic; using System.Globalization; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text.Json; using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; #endregion namespace Nemera.Plugins.MusicBrainz.Core.Api; /// /// HTTP client that calls the MusicBrainz web service and deserializes its JSON responses into typed response models. /// internal sealed class MusicBrainzHttpClient { private readonly HttpClient _httpClient; private readonly MusicBrainzSettingsProvider _settingsProvider; private readonly MusicBrainzRequestThrottle _requestThrottle; private readonly MusicBrainzResponseCache _responseCache; private static readonly JsonSerializerOptions s_serializerOptions = new(JsonSerializerDefaults.Web) { NumberHandling = JsonNumberHandling.AllowReadingFromString }; // Transient failures and rate limiting are retried with an exponential backoff, so a single hiccup does not mark an item as failed to enrich. private const int MAXIMUM_ATTEMPT_COUNT = 4; // The redirects of a self hosted mirror are followed explicitly, so the host redirect policy can be opted out of and only the same host can be reached. private const int MAXIMUM_REDIRECT_COUNT = 5; /// /// Initializes a new instance of the class. /// /// The used to send requests to the MusicBrainz web service. /// The provider of the settings that configure the MusicBrainz web service requests. /// The process-wide throttle that spaces out the requests sent to the MusicBrainz web service. /// The process-wide cache that avoids fetching the same entity more than once during a run. public MusicBrainzHttpClient(HttpClient httpClient, MusicBrainzSettingsProvider settingsProvider, MusicBrainzRequestThrottle requestThrottle, MusicBrainzResponseCache responseCache) { _httpClient = httpClient; _settingsProvider = settingsProvider; _requestThrottle = requestThrottle; _responseCache = responseCache; } /// /// Looks up the artist identified by . /// /// The MusicBrainz identifier of the artist. /// Cancellation token that can be used to stop the execution. /// The artist, or when no artist was found. public Task GetArtistAsync(Guid musicBrainzArtistId, CancellationToken cancellationToken) { return GetJsonOrNullAsync( $"artist/{musicBrainzArtistId:D}?inc=aliases+tags+genres+url-rels+artist-rels+ratings&fmt=json", cancellationToken); } /// /// Searches MusicBrainz for artists matching the provided query. /// /// The search query. /// The maximum number of results to return. /// Cancellation token that can be used to stop the execution. /// The list of matching artists. public async Task> SearchArtistsAsync(string query, int limit, CancellationToken cancellationToken) { MusicBrainzArtistSearchResponse? response = await GetJsonOrNullAsync( $"artist?query={Uri.EscapeDataString(query)}&limit={Math.Clamp(limit, 1, 100).ToString(CultureInfo.InvariantCulture)}&fmt=json", cancellationToken).ConfigureAwait(false); return response?.Artists ?? []; } /// /// Looks up the release group identified by . /// /// The MusicBrainz identifier of the release group. /// Cancellation token that can be used to stop the execution. /// The release group, or when no release group was found. public Task GetReleaseGroupAsync(Guid musicBrainzReleaseGroupId, CancellationToken cancellationToken) { return GetJsonOrNullAsync( $"release-group/{musicBrainzReleaseGroupId:D}?inc=artist-credits+tags+genres+ratings&fmt=json", cancellationToken); } /// /// Searches MusicBrainz for release groups matching the provided query. /// /// The search query. /// The maximum number of results to return. /// Cancellation token that can be used to stop the execution. /// The list of matching release groups. public async Task> SearchReleaseGroupsAsync(string query, int limit, CancellationToken cancellationToken) { MusicBrainzReleaseGroupSearchResponse? response = await GetJsonOrNullAsync( $"release-group?query={Uri.EscapeDataString(query)}&limit={Math.Clamp(limit, 1, 100).ToString(CultureInfo.InvariantCulture)}&fmt=json", cancellationToken).ConfigureAwait(false); return response?.ReleaseGroups ?? []; } /// /// Looks up the release identified by . /// /// The MusicBrainz identifier of the release. /// Cancellation token that can be used to stop the execution. /// The release, or when no release was found. public Task GetReleaseAsync(Guid musicBrainzReleaseId, CancellationToken cancellationToken) { return GetJsonOrNullAsync( $"release/{musicBrainzReleaseId:D}?inc=artist-credits+labels+release-groups+media+tags+genres+artist-rels&fmt=json", cancellationToken); } /// /// Browses the releases that belong to the release group identified by . /// /// The MusicBrainz identifier of the release group. /// The maximum number of releases to return. /// Cancellation token that can be used to stop the execution. /// The list of releases of the release group. public async Task> BrowseReleasesByReleaseGroupAsync(Guid musicBrainzReleaseGroupId, int limit, CancellationToken cancellationToken) { MusicBrainzReleaseBrowseResponse? response = await GetJsonOrNullAsync( $"release?release-group={musicBrainzReleaseGroupId:D}&inc=artist-credits+labels+media&limit={Math.Clamp(limit, 1, 100).ToString(CultureInfo.InvariantCulture)}&fmt=json", cancellationToken).ConfigureAwait(false); return response?.Releases ?? []; } /// /// Looks up the recording identified by . /// /// The MusicBrainz identifier of the recording. /// Cancellation token that can be used to stop the execution. /// The recording, or when no recording was found. public Task GetRecordingAsync(Guid musicBrainzRecordingId, CancellationToken cancellationToken) { return GetJsonOrNullAsync( $"recording/{musicBrainzRecordingId:D}?inc=artist-credits+isrcs+releases+tags+genres+work-rels+artist-rels+ratings&fmt=json", cancellationToken); } /// /// Searches MusicBrainz for recordings matching the provided query. /// /// The search query. /// The maximum number of results to return. /// Cancellation token that can be used to stop the execution. /// The list of matching recordings. public async Task> SearchRecordingsAsync(string query, int limit, CancellationToken cancellationToken) { MusicBrainzRecordingSearchResponse? response = await GetJsonOrNullAsync( $"recording?query={Uri.EscapeDataString(query)}&limit={Math.Clamp(limit, 1, 100).ToString(CultureInfo.InvariantCulture)}&fmt=json", cancellationToken).ConfigureAwait(false); return response?.Recordings ?? []; } /// /// Looks up the recordings that carry the provided ISRC. /// /// The ISRC to look up. /// Cancellation token that can be used to stop the execution. /// The list of recordings that carry the ISRC. public async Task> GetRecordingsByIsrcAsync(string isrc, CancellationToken cancellationToken) { MusicBrainzRecordingListResponse? response = await GetJsonOrNullAsync( $"isrc/{Uri.EscapeDataString(isrc)}?inc=artist-credits+isrcs+work-rels+artist-rels&fmt=json", cancellationToken).ConfigureAwait(false); return response?.Recordings ?? []; } /// /// Looks up the work identified by , together with its credited contributors. /// /// The MusicBrainz identifier of the work. /// Cancellation token that can be used to stop the execution. /// The work, or when no work was found. public Task GetWorkAsync(Guid musicBrainzWorkId, CancellationToken cancellationToken) { return GetJsonOrNullAsync( $"work/{musicBrainzWorkId:D}?inc=artist-rels+tags+genres&fmt=json", cancellationToken); } /// /// Looks up the release identified by , together with its media, tracks, recordings and all the data needed /// to enrich those tracks, so that every track of the release is enriched from a single request. /// /// The MusicBrainz identifier of the release. /// Cancellation token that can be used to stop the execution. /// The release, with its media, tracks and recordings, or when no release was found. public Task GetReleaseWithRecordingsAsync(Guid musicBrainzReleaseId, CancellationToken cancellationToken) { return GetJsonOrNullAsync( $"release/{musicBrainzReleaseId:D}?inc=recordings+isrcs+artist-credits+tags+genres+ratings+work-rels+recording-level-rels+work-level-rels+artist-rels+release-groups+labels+media&fmt=json", cancellationToken); } /// /// Gets the JSON resource at the given relative URL and deserializes it into . /// /// The type to deserialize the JSON response into. /// The URL of the resource, relative to the base address. /// Cancellation token that can be used to stop the execution. /// The deserialized resource, or when the resource was not found. /// Transient failures and rate limiting are handled by retrying the request up to three times. private async Task GetJsonOrNullAsync(string relativeUrl, CancellationToken cancellationToken) { MusicBrainzSettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false); string cacheKey = string.Concat(settings.BaseUrl, relativeUrl); if (_responseCache.TryGet(cacheKey, out string? cachedJson) && cachedJson is not null) return JsonSerializer.Deserialize(cachedJson, s_serializerOptions); using HttpResponseMessage response = await SendAsync(settings, relativeUrl, cancellationToken).ConfigureAwait(false); // A 404 means the entity does not exist in MusicBrainz, which is a normal miss rather than an error, so it is reported as no result. if (response.StatusCode == HttpStatusCode.NotFound) return default; response.EnsureSuccessStatusCode(); string json = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); _responseCache.Set(cacheKey, json); return JsonSerializer.Deserialize(json, s_serializerOptions); } /// /// Sends a GET request to the MusicBrainz web service, following its redirects explicitly so they are confined to the configured host, and throttled to /// respect the configured minimum request interval unless the configured base URL is not the real MusicBrainz service, in which case no rate limit is imposed. /// Transient failures, rate limiting and transport exceptions are retried, preferring the delay requested by the web service when it is provided. /// /// The settings that configure the MusicBrainz web service requests. /// The URL of the resource, relative to the base address. /// Cancellation token that can be used to stop the execution. /// The HTTP response message for the request. /// The service redirected the request to a host or a scheme that is not allowed, or too many times. private async Task SendAsync(MusicBrainzSettingsDto settings, string relativeUrl, CancellationToken cancellationToken) { Uri baseUri = new(settings.BaseUrl, UriKind.Absolute); // The permission to reach a private address is scoped to the host of the configured base URL, so a mirror cannot redirect the request to another // private host, and the link local and cloud metadata ranges stay blocked even when the permission is granted. string? allowedPrivateHost = settings.DoesAllowPrivateBaseUrl ? baseUri.IdnHost : null; Uri requestUri = BuildRequestUri(settings.BaseUrl, relativeUrl); for (int redirectCount = 0; redirectCount <= MAXIMUM_REDIRECT_COUNT; redirectCount++) { HttpResponseMessage response = await SendWithRetriesAsync(settings, requestUri, allowedPrivateHost, cancellationToken).ConfigureAwait(false); if (!IsRedirect(response.StatusCode) || response.Headers.Location is null) return response; Uri? redirectUri = ResolveRedirect(requestUri, response.Headers.Location); // The response of a redirect is not returned, so it must be disposed here to release its connection. response.Dispose(); // A redirect is followed only to the configured host, and never from HTTPS to HTTP, so a compromised or misbehaving mirror cannot redirect the // request to any other host, while a plain HTTP self hosted mirror keeps working across the redirects of its reverse proxy. if (redirectUri is null || !IsAllowedRedirect(baseUri, redirectUri)) throw new HttpRequestException(HttpRequestError.ConfigurationLimitExceeded, "The MusicBrainz service redirected the request to a disallowed target."); requestUri = redirectUri; } throw new HttpRequestException(HttpRequestError.ConfigurationLimitExceeded, "The MusicBrainz service redirected the request too many times."); } /// /// Sends a GET request to the provided URI, throttled to respect the configured minimum request interval. Transient failures and rate limiting are retried, /// so a single hiccup does not surface as a failed resolution. /// /// The settings that configure the MusicBrainz web service requests. /// The absolute URI of the resource to request. /// The host that may be private, or when no such permission was granted. /// Cancellation token that can be used to stop the execution. /// The HTTP response message for the request. private async Task SendWithRetriesAsync(MusicBrainzSettingsDto settings, Uri requestUri, string? allowedPrivateHost, CancellationToken cancellationToken) { EnsureRequestHeaders(settings); // The rate limit is enforced by the MusicBrainz web service itself, so it is only observed when the requests actually reach it; a self hosted // mirror, or any other configured base URL that is not the real service, is not limited by this process. bool shouldThrottle = IsRealMusicBrainzService(settings.BaseUrl); // A fresh request is created for every attempt, because an HTTP request cannot be sent more than once, and the throttle is applied to every // attempt, so that the retries of a failed request cannot burst past the rate limit of the real MusicBrainz web service. for (int attempt = 1; ; attempt++) { if (shouldThrottle) await _requestThrottle.WaitAsync(settings.MinimumRequestInterval, cancellationToken).ConfigureAwait(false); bool isLastAttempt = attempt >= MAXIMUM_ATTEMPT_COUNT; HttpResponseMessage response; try { HttpRequestMessage request = new(HttpMethod.Get, requestUri); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // The client follows the redirects itself, confined to the configured host, so it opts out of the host redirect handling. request.Options.Set(OutboundRequestOptions.FollowRedirects, false); if (allowedPrivateHost is not null && string.Equals(requestUri.IdnHost, allowedPrivateHost, StringComparison.OrdinalIgnoreCase)) request.Options.Set(OutboundRequestOptions.AllowedPrivateHost, allowedPrivateHost); response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); } catch (HttpRequestException exception) when (!isLastAttempt && !IsPolicyRejection(exception)) { // A rejection by the host outbound address policy is deterministic and is reported as ConfigurationLimitExceeded, so it is not retried. await Task.Delay(GetRetryDelay(attempt, null), cancellationToken).ConfigureAwait(false); continue; } if (!isLastAttempt && (response.StatusCode == HttpStatusCode.TooManyRequests || (int)response.StatusCode >= 500)) { TimeSpan retryDelay = GetRetryDelay(attempt, response); // The response of a failed attempt is not returned, so it must be disposed here to release its connection. response.Dispose(); await Task.Delay(retryDelay, cancellationToken).ConfigureAwait(false); continue; } return response; } } /// /// Determines whether the provided status code is a redirect. /// /// The status code to check. /// when the status code is a redirect, otherwise . private static bool IsRedirect(HttpStatusCode statusCode) { return statusCode is HttpStatusCode.MovedPermanently or HttpStatusCode.Found or HttpStatusCode.SeeOther or HttpStatusCode.TemporaryRedirect or HttpStatusCode.PermanentRedirect; } /// /// Resolves the location of a redirect against the URI of the request it was returned for. /// /// The URI of the request the redirect was returned for. /// The location of the redirect. /// The absolute URI of the redirect, or when it could not be resolved. private static Uri? ResolveRedirect(Uri requestUri, Uri location) { if (location.IsAbsoluteUri) return location; return Uri.TryCreate(requestUri, location, out Uri? resolvedUri) ? resolvedUri : null; } /// /// Determines whether the provided redirect target may be followed: it must stay on the host of the configured base address, and it may not downgrade an HTTPS base address to plain HTTP. /// /// The URI of the configured base address. /// The URI of the redirect target. /// when the redirect may be followed, otherwise . private static bool IsAllowedRedirect(Uri baseUri, Uri redirectUri) { bool isSchemeAllowed = redirectUri.Scheme == Uri.UriSchemeHttps || (baseUri.Scheme == Uri.UriSchemeHttp && redirectUri.Scheme == Uri.UriSchemeHttp); return isSchemeAllowed && string.Equals(baseUri.IdnHost, redirectUri.IdnHost, StringComparison.OrdinalIgnoreCase); } /// /// Gets the delay to wait before the next attempt, preferring the delay requested by the MusicBrainz web service when it is provided. /// /// The one based number of the attempt that just failed. /// The response of the failed attempt, when the failure was a response rather than a transport exception. /// The delay to wait before the next attempt. private static TimeSpan GetRetryDelay(int attempt, HttpResponseMessage? response) { if (response?.Headers.RetryAfter is { } retryAfter) { if (retryAfter.Delta is TimeSpan delta) return delta; if (retryAfter.Date is DateTimeOffset date) { TimeSpan wait = date - DateTimeOffset.UtcNow; if (wait > TimeSpan.Zero) return wait; } } return TimeSpan.FromMilliseconds(250 * Math.Pow(2, attempt)); } /// /// Determines whether the provided exception, or one of its inner exceptions, reports a rejection by the host outbound address policy. /// /// The exception to inspect. /// when the exception chain contains a policy rejection, otherwise . /// /// SocketsHttpHandler wraps an exception thrown by the connect callback in an HttpRequestException with the ConnectionError error, so the policy rejection is only visible on the inner exception. /// private static bool IsPolicyRejection(HttpRequestException exception) { for (Exception? currentException = exception; currentException is not null; currentException = currentException.InnerException) if (currentException is HttpRequestException httpRequestException && httpRequestException.HttpRequestError == HttpRequestError.ConfigurationLimitExceeded) return true; return false; } /// /// Determines whether the provided base URL points to the real MusicBrainz web service, which is the only one whose rate limit is observed. /// /// The base URL of the MusicBrainz web service the requests are sent to. /// when the base URL points to the real MusicBrainz web service, otherwise . private static bool IsRealMusicBrainzService(string baseUrl) { if (!Uri.TryCreate(baseUrl, UriKind.Absolute, out Uri? baseUri)) return false; return baseUri.Host.Equals("musicbrainz.org", StringComparison.OrdinalIgnoreCase) || baseUri.Host.EndsWith(".musicbrainz.org", StringComparison.OrdinalIgnoreCase); } /// /// Applies the request headers configured in the onto the underlying HTTP client, unless they are already set. /// /// The settings that configure the MusicBrainz web service requests. private void EnsureRequestHeaders(MusicBrainzSettingsDto settings) { // The headers live on the underlying HttpClient, which is reused across the calls of this client, so they are applied only once. if (_httpClient.DefaultRequestHeaders.UserAgent.Count == 0) { string userAgent = string.IsNullOrWhiteSpace(settings.ContactEmail) ? settings.UserAgent : $"{settings.UserAgent} ( {settings.ContactEmail} )"; _httpClient.DefaultRequestHeaders.UserAgent.ParseAdd(userAgent); } } /// /// Combines the configured base URL with the given relative URL into the absolute URI of a request. /// /// The base URL of the MusicBrainz web service the requests are sent to. /// The URL of the resource, relative to the base URL. /// The absolute URI of the request. private static Uri BuildRequestUri(string baseUrl, string relativeUrl) { string normalizedBaseUrl = baseUrl.EndsWith('/') ? baseUrl : string.Concat(baseUrl, "/"); return new Uri(new Uri(normalizedBaseUrl, UriKind.Absolute), relativeUrl); } }