1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
|
// <copyright file="TokenBucket.cs" company="JP Dillingham">
// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
// █__ --█ █__ --█ ◄█ - █
// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
// │ 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
// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
// </copyright>
namespace slskd
{
using System;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Implements the 'token bucket' or 'leaky bucket' rate limiting algorithm.
/// </summary>
public interface ITokenBucket
{
/// <summary>
/// Gets the bucket capacity.
/// </summary>
public long Capacity { get; }
/// <summary>
/// Asynchronously retrieves the specified token <paramref name="count"/> from the bucket.
/// </summary>
/// <remarks>
/// <para>
/// If the requested <paramref name="count"/> exceeds the bucket <see cref="Capacity"/>, the request is lowered to
/// the capacity of the bucket.
/// </para>
/// <para>If the bucket has tokens available, but fewer than the requested amount, the available tokens are returned.</para>
/// <para>
/// If the bucket has no tokens available, execution waits for the bucket to be replenished before servicing the request.
/// </para>
/// </remarks>
/// <param name="count">The number of tokens to retrieve.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>A Task that completes when tokens have been provided.</returns>
Task<int> GetAsync(int count, CancellationToken cancellationToken = default);
/// <summary>
/// Returns the specified token <paramref name="count"/> to the bucket.
/// </summary>
/// <remarks>
/// <para>This method should only be called if tokens were retrieved from the bucket, but were not used.</para>
/// <para>
/// 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.
/// </para>
/// <para>If the specified count is negative, no change is made to the available count.</para>
/// </remarks>
/// <param name="count">The number of tokens to return.</param>
void Return(int count);
/// <summary>
/// Sets the bucket capacity to the supplied <paramref name="capacity"/>.
/// </summary>
/// <remarks>Change takes effect on the next reset.</remarks>
/// <param name="capacity">The bucket capacity.</param>
void SetCapacity(long capacity);
}
/// <summary>
/// Implements the 'token bucket' or 'leaky bucket' rate limiting algorithm.
/// </summary>
public class TokenBucket : ITokenBucket, IDisposable
{
private TaskCompletionSource<bool> waitForReset = new(TaskCreationOptions.RunContinuationsAsynchronously);
/// <summary>
/// Initializes a new instance of the <see cref="TokenBucket"/> class.
/// </summary>
/// <param name="capacity">The bucket capacity.</param>
/// <param name="interval">The interval at which tokens are replenished, in milliseconds.</param>
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();
}
/// <summary>
/// Gets the bucket capacity.
/// </summary>
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);
/// <summary>
/// Disposes this instance.
/// </summary>
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Asynchronously retrieves the specified token <paramref name="count"/> from the bucket.
/// </summary>
/// <remarks>
/// <para>
/// If the requested <paramref name="count"/> exceeds the bucket <see cref="Capacity"/>, the request is lowered to
/// the capacity of the bucket.
/// </para>
/// <para>If the bucket has tokens available, but fewer than the requested amount, the available tokens are returned.</para>
/// <para>
/// If the bucket has no tokens available, execution waits for the bucket to be replenished before servicing the request.
/// </para>
/// </remarks>
/// <param name="count">The number of tokens to retrieve.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>A Task that completes when tokens have been provided.</returns>
public Task<int> GetAsync(int count, CancellationToken cancellationToken = default)
{
return GetInternalAsync(Math.Min(count, (int)Math.Min(int.MaxValue, Capacity)), cancellationToken);
}
/// <summary>
/// Returns the specified token <paramref name="count"/> to the bucket.
/// </summary>
/// <remarks>
/// <para>This method should only be called if tokens were retrieved from the bucket, but were not used.</para>
/// <para>
/// 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.
/// </para>
/// <para>If the specified count is negative, no change is made to the available count.</para>
/// </remarks>
/// <param name="count">The number of tokens to return.</param>
public void Return(int count)
{
CurrentCount += Math.Min(Math.Max(count, 0), Capacity);
}
/// <summary>
/// Sets the bucket capacity to the supplied <paramref name="capacity"/>.
/// </summary>
/// <remarks>Change takes effect on the next reset.</remarks>
/// <param name="capacity">The bucket capacity.</param>
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);
}
/// <summary>
/// Disposes this instance.
/// </summary>
/// <param name="disposing">A value indicating whether disposal is in progress.</param>
protected virtual void Dispose(bool disposing)
{
if (!Disposed)
{
if (disposing)
{
Clock.Dispose();
SyncRoot.Dispose();
}
Disposed = true;
}
}
private async Task<int> 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<bool>(TaskCreationOptions.RunContinuationsAsynchronously)).SetResult(true);
}
}
|