From c586e614c7894c8791541f1526d38a989160eaa0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 30 Jan 2022 18:24:39 -0600 Subject: add TokenBucket --- src/slskd/Common/TokenBucket.cs | 250 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 250 insertions(+) create mode 100644 src/slskd/Common/TokenBucket.cs (limited to 'src/slskd/Common/TokenBucket.cs') diff --git a/src/slskd/Common/TokenBucket.cs b/src/slskd/Common/TokenBucket.cs new file mode 100644 index 00000000..29fd720c --- /dev/null +++ b/src/slskd/Common/TokenBucket.cs @@ -0,0 +1,250 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// 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, either version 3 of the License, or +// (at your option) any later version. +// +// 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/. +// + +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 + { + /// + /// Initializes a new instance of the class. + /// + /// The bucket capacity. + /// The interval at which tokens are replenished. + 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) => _ = 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); + private TaskCompletionSource WaitForReset { get; set; } = new TaskCompletionSource(); + + /// + /// 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; + } + + /// + /// 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) + { + Task waitTask = Task.CompletedTask; + + await SyncRoot.WaitAsync(cancellationToken).ConfigureAwait(false); + + try + { + // if the bucket has enough tokens to fulfil the request, return them and decrement the bucket + if (CurrentCount >= count) + { + CurrentCount -= count; + return count; + } + + // if the bucket doesn't have enough tokens to fulfil the request, but has some available, return the available + // tokens and zero the bucket + if (CurrentCount > 0) + { + var availableCount = CurrentCount; + CurrentCount = 0; + return (int)availableCount; + } + + // if the bucket is empty, make the caller wait until the bucket is replenished + waitTask = WaitForReset.Task; + } + finally + { + SyncRoot.Release(); + } + + await waitTask.ConfigureAwait(false); + return await GetAsync(count, cancellationToken).ConfigureAwait(false); + } + + private async Task Reset() + { + await SyncRoot.WaitAsync().ConfigureAwait(false); + + try + { + CurrentCount = Capacity; + + WaitForReset.SetResult(true); + WaitForReset = new TaskCompletionSource(); + } + finally + { + SyncRoot.Release(); + } + } + } +} -- cgit v1.2.3 From 7dd7970bc9fcce6f4aaece6694ddbdb11eaa0f2a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 11 Feb 2022 08:08:25 -0600 Subject: update TokenBucket implementation --- src/slskd/Common/TokenBucket.cs | 54 ++++++++++++----------------------------- 1 file changed, 16 insertions(+), 38 deletions(-) (limited to 'src/slskd/Common/TokenBucket.cs') diff --git a/src/slskd/Common/TokenBucket.cs b/src/slskd/Common/TokenBucket.cs index 29fd720c..51a0281b 100644 --- a/src/slskd/Common/TokenBucket.cs +++ b/src/slskd/Common/TokenBucket.cs @@ -77,6 +77,8 @@ namespace slskd /// public class TokenBucket : ITokenBucket, IDisposable { + private TaskCompletionSource waitForReset = new(); + /// /// Initializes a new instance of the class. /// @@ -98,7 +100,7 @@ namespace slskd CurrentCount = Capacity; Clock = new System.Timers.Timer(interval); - Clock.Elapsed += (sender, e) => _ = Reset(); + Clock.Elapsed += (sender, e) => Reset(); Clock.Start(); } @@ -111,7 +113,6 @@ namespace slskd private long CurrentCount { get; set; } private bool Disposed { get; set; } private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); - private TaskCompletionSource WaitForReset { get; set; } = new TaskCompletionSource(); /// /// Disposes this instance. @@ -196,55 +197,32 @@ namespace slskd private async Task GetInternalAsync(int count, CancellationToken cancellationToken = default) { - Task waitTask = Task.CompletedTask; - await SyncRoot.WaitAsync(cancellationToken).ConfigureAwait(false); try { - // if the bucket has enough tokens to fulfil the request, return them and decrement the bucket - if (CurrentCount >= count) - { - CurrentCount -= count; - return count; - } - - // if the bucket doesn't have enough tokens to fulfil the request, but has some available, return the available - // tokens and zero the bucket - if (CurrentCount > 0) + // 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) { - var availableCount = CurrentCount; - CurrentCount = 0; - return (int)availableCount; + await waitForReset.Task.ConfigureAwait(false); + CurrentCount = Capacity; } - // if the bucket is empty, make the caller wait until the bucket is replenished - waitTask = WaitForReset.Task; + // 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(); } - - await waitTask.ConfigureAwait(false); - return await GetAsync(count, cancellationToken).ConfigureAwait(false); } - private async Task Reset() - { - await SyncRoot.WaitAsync().ConfigureAwait(false); - - try - { - CurrentCount = Capacity; - - WaitForReset.SetResult(true); - WaitForReset = new TaskCompletionSource(); - } - finally - { - SyncRoot.Release(); - } - } + private void Reset() + => Interlocked.Exchange(ref waitForReset, new TaskCompletionSource()).SetResult(true); } } -- cgit v1.2.3