Example #1
0
        public static RateLimitPair UpdateRateLimit(string baseUrl, RateLimit rateLimit)
        {
            if (string.IsNullOrEmpty(baseUrl))
            {
                return(null);
            }
            var existing = WaitForRateLimitDict.GetOrAdd(baseUrl, (f) => new RateLimitPair(rateLimit));

            existing.Update(rateLimit);
            return(existing);
        }
Example #2
0
            public RateLimitPair(RateLimit rateLimit)
            {
                var _resetTime      = rateLimit?.TimeToReset ?? DateTime.Now;
                var _callsRemaining = rateLimit?.CallsRemaining ?? 0;

                lock (_updateLock)
                {
                    if (_resetTime >= TimeToReset)
                    {
                        CallsRemaining = _callsRemaining;
                        TimeToReset    = _resetTime;
                    }
                }
            }
Example #3
0
            public void Update(RateLimit rateLimit)
            {
                if (rateLimit == null)
                {
                    return;
                }
                var _resetTime      = rateLimit.TimeToReset;
                var _callsRemaining = rateLimit.CallsRemaining;

                lock (_updateLock)
                {
                    if (_resetTime >= TimeToReset)
                    {
                        CallsRemaining = _callsRemaining;
                        TimeToReset    = _resetTime;
                    }
                }
            }
Example #4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="baseUrl"></param>
        /// <param name="cancellationToken"></param>
        /// <exception cref="TaskCanceledException"></exception>
        /// <returns></returns>
        public static async Task WaitForRateLimit(string baseUrl, RateLimit rateLimit, CancellationToken cancellationToken)
        {
            var existing = UpdateRateLimit(baseUrl, rateLimit);

            if (existing == null || existing.CallsRemaining > 0)
            {
                return;
            }
            TimeSpan delay = existing.TimeToReset - DateTime.Now;

            if (delay <= TimeSpan.Zero) // Make sure the delay is > 0
            {
                return;
            }
            else
            {
                Logger?.Debug($"Preemptively waiting {delay.Seconds} seconds for rate limit.");
            }

            await Task.Delay(delay, cancellationToken).ConfigureAwait(false);

            return;
        }