//
// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
// █__ --█ █__ --█ ◄█ - █
// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
// │ Copyright (c) JP Dillingham.
// │
// │ This program is free software: you can redistribute it and/or modify
// │ it under the terms of the GNU Affero General Public License as published
// │ by the Free Software Foundation, version 3.
// │
// │ This program is distributed in the hope that it will be useful,
// │ but WITHOUT ANY WARRANTY; without even the implied warranty of
// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// │ GNU Affero General Public License for more details.
// │
// │ You should have received a copy of the GNU Affero General Public License
// │ along with this program. If not, see https://www.gnu.org/licenses/.
// │
// │ This program is distributed with Additional Terms pursuant to Section 7
// │ of the AGPLv3. See the LICENSE file in the root directory of this
// │ project for the complete terms and conditions.
// │
// │ https://slskd.org
// │
// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
// │ SPDX-FileCopyrightText: JP Dillingham
// │ SPDX-License-Identifier: AGPL-3.0-only
// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
//
namespace slskd
{
using System;
using System.Threading;
using System.Threading.Tasks;
///
/// Implements the 'token bucket' or 'leaky bucket' rate limiting algorithm.
///
public interface ITokenBucket
{
///
/// Gets the bucket capacity.
///
public long Capacity { get; }
///
/// Asynchronously retrieves the specified token from the bucket.
///
///
///
/// If the requested exceeds the bucket , the request is lowered to
/// the capacity of the bucket.
///
/// If the bucket has tokens available, but fewer than the requested amount, the available tokens are returned.
///
/// If the bucket has no tokens available, execution waits for the bucket to be replenished before servicing the request.
///
///
/// The number of tokens to retrieve.
/// The token to monitor for cancellation requests.
/// A Task that completes when tokens have been provided.
Task GetAsync(int count, CancellationToken cancellationToken = default);
///
/// Returns the specified token to the bucket.
///
///
/// This method should only be called if tokens were retrieved from the bucket, but were not used.
///
/// If the specified count exceeds the bucket capacity, the count is lowered to the capacity. Effectively this
/// allows the bucket to 'burst' up to 2x capacity to 'catch up' to the desired rate if tokens were wastefully
/// retrieved.
///
/// If the specified count is negative, no change is made to the available count.
///
/// The number of tokens to return.
void Return(int count);
///
/// Sets the bucket capacity to the supplied .
///
/// Change takes effect on the next reset.
/// The bucket capacity.
void SetCapacity(long capacity);
}
///
/// Implements the 'token bucket' or 'leaky bucket' rate limiting algorithm.
///
public class TokenBucket : ITokenBucket, IDisposable
{
private TaskCompletionSource waitForReset = new(TaskCreationOptions.RunContinuationsAsynchronously);
///
/// Initializes a new instance of the class.
///
/// The bucket capacity.
/// The interval at which tokens are replenished, in milliseconds.
public TokenBucket(long capacity, int interval)
{
if (capacity < 1)
{
throw new ArgumentOutOfRangeException(nameof(capacity), "Bucket capacity must be greater than or equal to 1");
}
if (interval < 1)
{
throw new ArgumentOutOfRangeException(nameof(interval), "Interval must be greater than or equal to 1");
}
Capacity = capacity;
CurrentCount = Capacity;
Clock = new System.Timers.Timer(interval);
Clock.Elapsed += (sender, e) =>
{
CurrentCount = Capacity;
Reset();
};
Clock.Start();
}
///
/// Gets the bucket capacity.
///
public long Capacity { get; private set; }
private System.Timers.Timer Clock { get; set; }
private long CurrentCount { get; set; }
private bool Disposed { get; set; }
private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1);
///
/// Disposes this instance.
///
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
///
/// Asynchronously retrieves the specified token from the bucket.
///
///
///
/// If the requested exceeds the bucket , the request is lowered to
/// the capacity of the bucket.
///
/// If the bucket has tokens available, but fewer than the requested amount, the available tokens are returned.
///
/// If the bucket has no tokens available, execution waits for the bucket to be replenished before servicing the request.
///
///
/// The number of tokens to retrieve.
/// The token to monitor for cancellation requests.
/// A Task that completes when tokens have been provided.
public Task GetAsync(int count, CancellationToken cancellationToken = default)
{
return GetInternalAsync(Math.Min(count, (int)Math.Min(int.MaxValue, Capacity)), cancellationToken);
}
///
/// Returns the specified token to the bucket.
///
///
/// This method should only be called if tokens were retrieved from the bucket, but were not used.
///
/// If the specified count exceeds the bucket capacity, the count is lowered to the capacity. Effectively this
/// allows the bucket to 'burst' up to 2x capacity to 'catch up' to the desired rate if tokens were wastefully
/// retrieved.
///
/// If the specified count is negative, no change is made to the available count.
///
/// The number of tokens to return.
public void Return(int count)
{
CurrentCount += Math.Min(Math.Max(count, 0), Capacity);
}
///
/// Sets the bucket capacity to the supplied .
///
/// Change takes effect on the next reset.
/// The bucket capacity.
public void SetCapacity(long capacity)
{
if (capacity < 1)
{
throw new ArgumentOutOfRangeException(nameof(capacity), "Bucket capacity must be greater than or equal to 1");
}
Capacity = capacity;
CurrentCount = Math.Min(CurrentCount, Capacity);
}
///
/// Disposes this instance.
///
/// A value indicating whether disposal is in progress.
protected virtual void Dispose(bool disposing)
{
if (!Disposed)
{
if (disposing)
{
Clock.Dispose();
SyncRoot.Dispose();
}
Disposed = true;
}
}
private async Task GetInternalAsync(int count, CancellationToken cancellationToken = default)
{
await SyncRoot.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
// if the bucket is empty, wait for a reset, then replenish it before continuing
// this ensures tokens are distributed in the order in which callers obtain the semaphore,
// which is as close to a FIFO as .NET synchronization primitives will allow
if (CurrentCount == 0)
{
await waitForReset.Task.ConfigureAwait(false);
}
// take the minimum of requested count or CurrentCount, deduct it from
// CurrentCount (potentially zeroing the bucket), and return it
var availableCount = Math.Min(CurrentCount, count);
CurrentCount -= availableCount;
return (int)availableCount;
}
finally
{
SyncRoot.Release();
}
}
private void Reset()
=> Interlocked.Exchange(ref waitForReset, new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously)).SetResult(true);
}
}