#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings;
using Lumina.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 Lumina.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;
///
/// 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, 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.
private async Task SendAsync(MusicBrainzSettingsDto settings, string relativeUrl, 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, BuildRequestUri(settings.BaseUrl, relativeUrl));
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
}
catch (HttpRequestException) when (!isLastAttempt)
{
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;
}
}
///
/// 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 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);
}
}