mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 18:21:10 +00:00
Adds the MusicBrainz music metadata plugin, its fixtures, and its unit test suite
This commit is contained in:
1 parent
1ffa14cec4
commit
0abda472c6
101 files changed
+11461
No files matched your search
@@ -0,0 +1,336 @@
|
||||
#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;
|
||||
|
||||
/// <summary>
|
||||
/// HTTP client that calls the MusicBrainz web service and deserializes its JSON responses into typed response models.
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MusicBrainzHttpClient"/> class.
|
||||
/// </summary>
|
||||
/// <param name="httpClient">The <see cref="HttpClient"/> used to send requests to the MusicBrainz web service.</param>
|
||||
/// <param name="settingsProvider">The provider of the settings that configure the MusicBrainz web service requests.</param>
|
||||
/// <param name="requestThrottle">The process-wide throttle that spaces out the requests sent to the MusicBrainz web service.</param>
|
||||
/// <param name="responseCache">The process-wide cache that avoids fetching the same entity more than once during a run.</param>
|
||||
public MusicBrainzHttpClient(HttpClient httpClient, MusicBrainzSettingsProvider settingsProvider, MusicBrainzRequestThrottle requestThrottle, MusicBrainzResponseCache responseCache)
|
||||
{
|
||||
_httpClient = httpClient;
|
||||
_settingsProvider = settingsProvider;
|
||||
_requestThrottle = requestThrottle;
|
||||
_responseCache = responseCache;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up the artist identified by <paramref name="musicBrainzArtistId"/>.
|
||||
/// </summary>
|
||||
/// <param name="musicBrainzArtistId">The MusicBrainz identifier of the artist.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The artist, or <see langword="null"/> when no artist was found.</returns>
|
||||
public Task<MusicBrainzArtistResponse?> GetArtistAsync(Guid musicBrainzArtistId, CancellationToken cancellationToken)
|
||||
{
|
||||
return GetJsonOrNullAsync<MusicBrainzArtistResponse>(
|
||||
$"artist/{musicBrainzArtistId:D}?inc=aliases+tags+genres+url-rels+artist-rels+ratings&fmt=json", cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Searches MusicBrainz for artists matching the provided query.
|
||||
/// </summary>
|
||||
/// <param name="query">The search query.</param>
|
||||
/// <param name="limit">The maximum number of results to return.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The list of matching artists.</returns>
|
||||
public async Task<IReadOnlyList<MusicBrainzArtistResponse>> SearchArtistsAsync(string query, int limit, CancellationToken cancellationToken)
|
||||
{
|
||||
MusicBrainzArtistSearchResponse? response = await GetJsonOrNullAsync<MusicBrainzArtistSearchResponse>(
|
||||
$"artist?query={Uri.EscapeDataString(query)}&limit={Math.Clamp(limit, 1, 100).ToString(CultureInfo.InvariantCulture)}&fmt=json",
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
return response?.Artists ?? [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up the release group identified by <paramref name="musicBrainzReleaseGroupId"/>.
|
||||
/// </summary>
|
||||
/// <param name="musicBrainzReleaseGroupId">The MusicBrainz identifier of the release group.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The release group, or <see langword="null"/> when no release group was found.</returns>
|
||||
public Task<MusicBrainzReleaseGroupResponse?> GetReleaseGroupAsync(Guid musicBrainzReleaseGroupId, CancellationToken cancellationToken)
|
||||
{
|
||||
return GetJsonOrNullAsync<MusicBrainzReleaseGroupResponse>(
|
||||
$"release-group/{musicBrainzReleaseGroupId:D}?inc=artist-credits+tags+genres+ratings&fmt=json", cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Searches MusicBrainz for release groups matching the provided query.
|
||||
/// </summary>
|
||||
/// <param name="query">The search query.</param>
|
||||
/// <param name="limit">The maximum number of results to return.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The list of matching release groups.</returns>
|
||||
public async Task<IReadOnlyList<MusicBrainzReleaseGroupResponse>> SearchReleaseGroupsAsync(string query, int limit, CancellationToken cancellationToken)
|
||||
{
|
||||
MusicBrainzReleaseGroupSearchResponse? response = await GetJsonOrNullAsync<MusicBrainzReleaseGroupSearchResponse>(
|
||||
$"release-group?query={Uri.EscapeDataString(query)}&limit={Math.Clamp(limit, 1, 100).ToString(CultureInfo.InvariantCulture)}&fmt=json",
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
return response?.ReleaseGroups ?? [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up the release identified by <paramref name="musicBrainzReleaseId"/>.
|
||||
/// </summary>
|
||||
/// <param name="musicBrainzReleaseId">The MusicBrainz identifier of the release.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The release, or <see langword="null"/> when no release was found.</returns>
|
||||
public Task<MusicBrainzReleaseResponse?> GetReleaseAsync(Guid musicBrainzReleaseId, CancellationToken cancellationToken)
|
||||
{
|
||||
return GetJsonOrNullAsync<MusicBrainzReleaseResponse>(
|
||||
$"release/{musicBrainzReleaseId:D}?inc=artist-credits+labels+release-groups+media+tags+genres+artist-rels&fmt=json", cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Browses the releases that belong to the release group identified by <paramref name="musicBrainzReleaseGroupId"/>.
|
||||
/// </summary>
|
||||
/// <param name="musicBrainzReleaseGroupId">The MusicBrainz identifier of the release group.</param>
|
||||
/// <param name="limit">The maximum number of releases to return.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The list of releases of the release group.</returns>
|
||||
public async Task<IReadOnlyList<MusicBrainzReleaseResponse>> BrowseReleasesByReleaseGroupAsync(Guid musicBrainzReleaseGroupId, int limit, CancellationToken cancellationToken)
|
||||
{
|
||||
MusicBrainzReleaseBrowseResponse? response = await GetJsonOrNullAsync<MusicBrainzReleaseBrowseResponse>(
|
||||
$"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 ?? [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up the recording identified by <paramref name="musicBrainzRecordingId"/>.
|
||||
/// </summary>
|
||||
/// <param name="musicBrainzRecordingId">The MusicBrainz identifier of the recording.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The recording, or <see langword="null"/> when no recording was found.</returns>
|
||||
public Task<MusicBrainzRecordingResponse?> GetRecordingAsync(Guid musicBrainzRecordingId, CancellationToken cancellationToken)
|
||||
{
|
||||
return GetJsonOrNullAsync<MusicBrainzRecordingResponse>(
|
||||
$"recording/{musicBrainzRecordingId:D}?inc=artist-credits+isrcs+releases+tags+genres+work-rels+artist-rels+ratings&fmt=json", cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Searches MusicBrainz for recordings matching the provided query.
|
||||
/// </summary>
|
||||
/// <param name="query">The search query.</param>
|
||||
/// <param name="limit">The maximum number of results to return.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The list of matching recordings.</returns>
|
||||
public async Task<IReadOnlyList<MusicBrainzRecordingResponse>> SearchRecordingsAsync(string query, int limit, CancellationToken cancellationToken)
|
||||
{
|
||||
MusicBrainzRecordingSearchResponse? response = await GetJsonOrNullAsync<MusicBrainzRecordingSearchResponse>(
|
||||
$"recording?query={Uri.EscapeDataString(query)}&limit={Math.Clamp(limit, 1, 100).ToString(CultureInfo.InvariantCulture)}&fmt=json",
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
return response?.Recordings ?? [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up the recordings that carry the provided ISRC.
|
||||
/// </summary>
|
||||
/// <param name="isrc">The ISRC to look up.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The list of recordings that carry the ISRC.</returns>
|
||||
public async Task<IReadOnlyList<MusicBrainzRecordingResponse>> GetRecordingsByIsrcAsync(string isrc, CancellationToken cancellationToken)
|
||||
{
|
||||
MusicBrainzRecordingListResponse? response = await GetJsonOrNullAsync<MusicBrainzRecordingListResponse>(
|
||||
$"isrc/{Uri.EscapeDataString(isrc)}?inc=artist-credits+isrcs+work-rels+artist-rels&fmt=json", cancellationToken).ConfigureAwait(false);
|
||||
return response?.Recordings ?? [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up the work identified by <paramref name="musicBrainzWorkId"/>, together with its credited contributors.
|
||||
/// </summary>
|
||||
/// <param name="musicBrainzWorkId">The MusicBrainz identifier of the work.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The work, or <see langword="null"/> when no work was found.</returns>
|
||||
public Task<MusicBrainzWorkResponse?> GetWorkAsync(Guid musicBrainzWorkId, CancellationToken cancellationToken)
|
||||
{
|
||||
return GetJsonOrNullAsync<MusicBrainzWorkResponse>(
|
||||
$"work/{musicBrainzWorkId:D}?inc=artist-rels+tags+genres&fmt=json", cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up the release identified by <paramref name="musicBrainzReleaseId"/>, 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.
|
||||
/// </summary>
|
||||
/// <param name="musicBrainzReleaseId">The MusicBrainz identifier of the release.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The release, with its media, tracks and recordings, or <see langword="null"/> when no release was found.</returns>
|
||||
public Task<MusicBrainzReleaseResponse?> GetReleaseWithRecordingsAsync(Guid musicBrainzReleaseId, CancellationToken cancellationToken)
|
||||
{
|
||||
return GetJsonOrNullAsync<MusicBrainzReleaseResponse>(
|
||||
$"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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the JSON resource at the given relative URL and deserializes it into <typeparamref name="TModel"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TModel">The type to deserialize the JSON response into.</typeparam>
|
||||
/// <param name="relativeUrl">The URL of the resource, relative to the base address.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The deserialized resource, or <see langword="null"/> when the resource was not found.</returns>
|
||||
/// <remarks>Transient failures and rate limiting are handled by retrying the request up to three times.</remarks>
|
||||
private async Task<TModel?> GetJsonOrNullAsync<TModel>(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<TModel>(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<TModel>(json, s_serializerOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="settings">The settings that configure the MusicBrainz web service requests.</param>
|
||||
/// <param name="relativeUrl">The URL of the resource, relative to the base address.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The HTTP response message for the request.</returns>
|
||||
private async Task<HttpResponseMessage> 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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the delay to wait before the next attempt, preferring the delay requested by the MusicBrainz web service when it is provided.
|
||||
/// </summary>
|
||||
/// <param name="attempt">The one based number of the attempt that just failed.</param>
|
||||
/// <param name="response">The response of the failed attempt, when the failure was a response rather than a transport exception.</param>
|
||||
/// <returns>The delay to wait before the next attempt.</returns>
|
||||
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));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the provided base URL points to the real MusicBrainz web service, which is the only one whose rate limit is observed.
|
||||
/// </summary>
|
||||
/// <param name="baseUrl">The base URL of the MusicBrainz web service the requests are sent to.</param>
|
||||
/// <returns><see langword="true"/> when the base URL points to the real MusicBrainz web service, otherwise <see langword="false"/>.</returns>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies the request headers configured in the <paramref name="settings"/> onto the underlying HTTP client, unless they are already set.
|
||||
/// </summary>
|
||||
/// <param name="settings">The settings that configure the MusicBrainz web service requests.</param>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Combines the configured base URL with the given relative URL into the absolute URI of a request.
|
||||
/// </summary>
|
||||
/// <param name="baseUrl">The base URL of the MusicBrainz web service the requests are sent to.</param>
|
||||
/// <param name="relativeUrl">The URL of the resource, relative to the base URL.</param>
|
||||
/// <returns>The absolute URI of the request.</returns>
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.Core.Api;
|
||||
|
||||
/// <summary>
|
||||
/// Spaces out the requests sent to the MusicBrainz web service, so the configured minimum request interval is respected across every caller in the process.
|
||||
/// </summary>
|
||||
internal sealed class MusicBrainzRequestThrottle
|
||||
{
|
||||
private readonly SemaphoreSlim _gate = new(1, 1);
|
||||
|
||||
// The timestamp of the last reserved request slot, shared process wide, so the configured interval is enforced between requests no matter
|
||||
// which caller sends them.
|
||||
private DateTimeOffset _lastRequestAt = DateTimeOffset.MinValue;
|
||||
|
||||
/// <summary>
|
||||
/// Waits until the minimum interval elapsed since the previous reserved request, then reserves the next request slot.
|
||||
/// </summary>
|
||||
/// <param name="minimumRequestInterval">The minimum amount of time that must elapse between two consecutive requests.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>A task that completes once the caller may send its request.</returns>
|
||||
public async Task WaitAsync(TimeSpan minimumRequestInterval, CancellationToken cancellationToken)
|
||||
{
|
||||
// The gate is held across the delay, so concurrent callers queue up and each one is released only once the interval elapsed since the
|
||||
// previous reserved slot.
|
||||
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
// A non positive interval means the callers are not spaced out at all, and it must not be added to the initial timestamp, which would underflow it.
|
||||
if (minimumRequestInterval > TimeSpan.Zero)
|
||||
{
|
||||
DateTimeOffset earliestNextRequest = _lastRequestAt + minimumRequestInterval;
|
||||
TimeSpan delay = earliestNextRequest - DateTimeOffset.UtcNow;
|
||||
if (delay > TimeSpan.Zero)
|
||||
await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
_lastRequestAt = DateTimeOffset.UtcNow;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.Core.Api;
|
||||
|
||||
/// <summary>
|
||||
/// In-memory cache of the responses returned by the MusicBrainz web service, keyed by the requested URL.
|
||||
/// It removes the repeated lookups of the same entity during a run, and expires its entries after a bounded time.
|
||||
/// </summary>
|
||||
internal sealed class MusicBrainzResponseCache
|
||||
{
|
||||
/// <summary>
|
||||
/// The maximum number of responses the cache keeps.
|
||||
/// </summary>
|
||||
internal const int MAXIMUM_ENTRY_COUNT = 20_000;
|
||||
|
||||
/// <summary>
|
||||
/// The maximum total number of characters of the cached response bodies.
|
||||
/// </summary>
|
||||
internal const long MAXIMUM_CHARACTER_COUNT = 100_000_000;
|
||||
|
||||
/// <summary>
|
||||
/// The percentage of a budget that the cache is trimmed down to when it exceeds that budget. Trimming to a lower water mark keeps the
|
||||
/// eviction from running on every write once a budget is reached.
|
||||
/// </summary>
|
||||
private const int TRIM_TARGET_PERCENT = 90;
|
||||
|
||||
private static readonly TimeSpan s_timeToLive = TimeSpan.FromMinutes(15);
|
||||
|
||||
private readonly int _maximumEntryCount;
|
||||
private readonly long _maximumCharacterCount;
|
||||
private readonly TimeSpan _timeToLive;
|
||||
private readonly ConcurrentDictionary<string, CacheEntry> _entries = new(StringComparer.Ordinal);
|
||||
|
||||
// The dictionary is thread safe on its own, but the character budget is a read modify write over it, so the size bookkeeping and the eviction
|
||||
// are guarded by a lock, while reads stay lock free.
|
||||
private readonly Lock _sizeGate = new();
|
||||
private long _cachedCharacterCount;
|
||||
|
||||
// Monotonically increasing insertion stamp, used to evict the oldest entries first.
|
||||
private long _sequence;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MusicBrainzResponseCache"/> class with the default budgets and time to live.
|
||||
/// </summary>
|
||||
public MusicBrainzResponseCache()
|
||||
{
|
||||
_maximumEntryCount = MAXIMUM_ENTRY_COUNT;
|
||||
_maximumCharacterCount = MAXIMUM_CHARACTER_COUNT;
|
||||
_timeToLive = s_timeToLive;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MusicBrainzResponseCache"/> class with the provided budgets and time to live.
|
||||
/// </summary>
|
||||
/// <param name="maximumEntryCount">The maximum number of responses the cache keeps.</param>
|
||||
/// <param name="maximumCharacterCount">The maximum total number of characters of the cached response bodies.</param>
|
||||
/// <param name="timeToLive">The amount of time a cached response stays valid.</param>
|
||||
internal MusicBrainzResponseCache(int maximumEntryCount, long maximumCharacterCount, TimeSpan timeToLive)
|
||||
{
|
||||
_maximumEntryCount = maximumEntryCount;
|
||||
_maximumCharacterCount = maximumCharacterCount;
|
||||
_timeToLive = timeToLive;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to get the cached response body for <paramref name="key"/>.
|
||||
/// </summary>
|
||||
/// <param name="key">The key of the cached response.</param>
|
||||
/// <param name="json">The cached response body, when found.</param>
|
||||
/// <returns><see langword="true"/> when an unexpired response was found, otherwise <see langword="false"/>.</returns>
|
||||
public bool TryGet(string key, out string? json)
|
||||
{
|
||||
// An expired entry is treated as a miss instead of being removed here, so readers never take the lock; a later write reclaims it.
|
||||
if (_entries.TryGetValue(key, out CacheEntry? entry) && entry.ExpiresOnUtc > DateTime.UtcNow)
|
||||
{
|
||||
json = entry.Json;
|
||||
return true;
|
||||
}
|
||||
json = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds or replaces the cached response body for <paramref name="key"/>, then trims the cache back to its budgets.
|
||||
/// </summary>
|
||||
/// <param name="key">The key of the cached response.</param>
|
||||
/// <param name="json">The response body to cache.</param>
|
||||
public void Set(string key, string json)
|
||||
{
|
||||
// A single response larger than the whole character budget can never be admitted, so it is rejected before it disturbs the cache.
|
||||
if (json.Length > _maximumCharacterCount)
|
||||
return;
|
||||
|
||||
lock (_sizeGate)
|
||||
{
|
||||
if (_entries.TryRemove(key, out CacheEntry? existing))
|
||||
_cachedCharacterCount -= existing.Json.Length;
|
||||
|
||||
_entries[key] = new CacheEntry(json, DateTime.UtcNow.Add(_timeToLive), ++_sequence);
|
||||
_cachedCharacterCount += json.Length;
|
||||
|
||||
if (_entries.Count > _maximumEntryCount || _cachedCharacterCount > _maximumCharacterCount)
|
||||
TrimToBudget();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the expired entries, and then the oldest unexpired entries, until the cache is back within its entry count and character budgets.
|
||||
/// </summary>
|
||||
private void TrimToBudget()
|
||||
{
|
||||
DateTime utcNow = DateTime.UtcNow;
|
||||
bool isOverEntryCount = _entries.Count > _maximumEntryCount;
|
||||
bool isOverCharacterCount = _cachedCharacterCount > _maximumCharacterCount;
|
||||
int entryTarget = Math.Max(1, _maximumEntryCount * TRIM_TARGET_PERCENT / 100);
|
||||
long characterTarget = Math.Max(1, _maximumCharacterCount * TRIM_TARGET_PERCENT / 100);
|
||||
|
||||
// Entries are evicted in insertion order, so the most recently cached responses survive; an expired entry is always removed, even when
|
||||
// a budget was not exceeded, so the cache keeps reclaiming dead entries.
|
||||
foreach (KeyValuePair<string, CacheEntry> candidate in _entries.OrderBy(entry => entry.Value.Sequence))
|
||||
{
|
||||
bool isExpired = candidate.Value.ExpiresOnUtc <= utcNow;
|
||||
bool needsEntryTrim = isOverEntryCount && _entries.Count > entryTarget;
|
||||
bool needsCharacterTrim = isOverCharacterCount && _cachedCharacterCount > characterTarget;
|
||||
if (!isExpired && !needsEntryTrim && !needsCharacterTrim)
|
||||
break;
|
||||
|
||||
if (_entries.TryRemove(candidate.Key, out CacheEntry? removed))
|
||||
_cachedCharacterCount -= removed.Json.Length;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed record CacheEntry(string Json, DateTime ExpiresOnUtc, long Sequence);
|
||||
}
|
||||
Reference in new issue
Block a user