diff --git a/MetaBrainz.MusicBrainz/Query.Internals.cs b/MetaBrainz.MusicBrainz/Query.Internals.cs index be8f224..b212a79 100644 --- a/MetaBrainz.MusicBrainz/Query.Internals.cs +++ b/MetaBrainz.MusicBrainz/Query.Internals.cs @@ -532,6 +532,14 @@ private async Task PerformRequestAsync(Uri uri, HttpMethod Debug.Print($"[{DateTime.UtcNow}] => HEADERS: {TextUtils.FormatMultiLine(response.Headers.ToString())}"); Debug.Print($"[{DateTime.UtcNow}] => CONTENT ({response.Content.Headers.ContentType}): " + $"{response.Content.Headers.ContentLength ?? 0} bytes"); + var rateLimitInfo = new RateLimitInfo(response.Headers); + this._rateLimitLock.EnterWriteLock(); + try { + this._rateLimitInfo = rateLimitInfo; + } + finally { + this._rateLimitLock.ExitWriteLock(); + } if (!response.IsSuccessStatusCode) { throw await QueryException.FromResponseAsync(response, cancellationToken).ConfigureAwait(false); } diff --git a/MetaBrainz.MusicBrainz/Query.cs b/MetaBrainz.MusicBrainz/Query.cs index 269187b..23a56c7 100644 --- a/MetaBrainz.MusicBrainz/Query.cs +++ b/MetaBrainz.MusicBrainz/Query.cs @@ -2,9 +2,12 @@ using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Headers; +using System.Threading; using JetBrains.Annotations; +using MetaBrainz.Common; + namespace MetaBrainz.MusicBrainz; /// Class providing access to the MusicBrainz API. @@ -77,7 +80,8 @@ public static string DefaultUrlScheme { /// /// /// Note that this is a global delay, affecting all threads. When querying the official MusicBrainz site, setting this below the - /// default of one second may incur penalties (ranging from rate limiting to IP bans). + /// default of one second may incur penalties (ranging from rate limiting to IP bans). When setting this to 0 for maximum + /// throughput, can be used to avoid making too many requests and trigger these penalties. /// public static double DelayBetweenRequests { get; set; } = 1.0; @@ -209,6 +213,27 @@ public int Port { } } + private RateLimitInfo _rateLimitInfo; + + private readonly ReaderWriterLockSlim _rateLimitLock = new(); + + /// The rate limit information from the last web request issued via this MusicBrainz client. + /// + /// This is mainly useful when setting to 0, in order to manage the request volume to avoid + /// triggering penalties. + /// + public RateLimitInfo RateLimitInfo { + get { + this._rateLimitLock.EnterReadLock(); + try { + return this._rateLimitInfo; + } + finally { + this._rateLimitLock.ExitReadLock(); + } + } + } + private string _server = Query.DefaultServer; /// The web site to use for requests.