-
Notifications
You must be signed in to change notification settings - Fork 5.4k
Expand file tree
/
Copy pathDefaultPartitionedRateLimiter.cs
More file actions
288 lines (254 loc) · 10.4 KB
/
DefaultPartitionedRateLimiter.cs
File metadata and controls
288 lines (254 loc) · 10.4 KB
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace System.Threading.RateLimiting
{
internal sealed class DefaultPartitionedRateLimiter<TResource, TKey> : PartitionedRateLimiter<TResource> where TKey : notnull
{
private readonly Func<TResource, RateLimitPartition<TKey>> _partitioner;
private static readonly TimeSpan s_idleTimeLimit = TimeSpan.FromSeconds(10);
// TODO: Look at ConcurrentDictionary to try and avoid a global lock
private readonly Dictionary<TKey, Lazy<RateLimiter>> _limiters;
private bool _disposed;
private readonly TaskCompletionSource<object?> _disposeComplete = new(TaskCreationOptions.RunContinuationsAsynchronously);
// Used by the Timer to call TryRelenish on ReplenishingRateLimiters
// We use a separate list to avoid running TryReplenish (which might be user code) inside our lock
// And we cache the list to amortize the allocation cost to as close to 0 as we can get
private readonly List<KeyValuePair<TKey, Lazy<RateLimiter>>> _cachedLimiters = new();
private bool _cacheInvalid;
private readonly List<RateLimiter> _limitersToDispose = new();
private readonly TimerAwaitable _timer;
private readonly Task _timerTask;
// Use the Dictionary as the lock field so we don't need to allocate another object for a lock and have another field in the object
private object Lock => _limiters;
public DefaultPartitionedRateLimiter(Func<TResource, RateLimitPartition<TKey>> partitioner,
IEqualityComparer<TKey>? equalityComparer = null)
: this(partitioner, equalityComparer, TimeSpan.FromMilliseconds(100))
{
}
// Extra ctor for testing purposes, primarily used when wanting to test the timer manually
private DefaultPartitionedRateLimiter(Func<TResource, RateLimitPartition<TKey>> partitioner,
IEqualityComparer<TKey>? equalityComparer, TimeSpan timerInterval)
{
_limiters = new Dictionary<TKey, Lazy<RateLimiter>>(equalityComparer);
_partitioner = partitioner;
_timer = new TimerAwaitable(timerInterval, timerInterval);
_timerTask = RunTimer();
}
private async Task RunTimer()
{
_timer.Start();
while (await _timer)
{
try
{
await Heartbeat().ConfigureAwait(
#if NET8_0_OR_GREATER
ConfigureAwaitOptions.SuppressThrowing
#else
false
#endif
);
}
catch { }
}
_timer.Dispose();
}
public override RateLimiterStatistics? GetStatistics(TResource resource)
{
return GetRateLimiter(resource).GetStatistics();
}
protected override RateLimitLease AttemptAcquireCore(TResource resource, int permitCount)
{
return GetRateLimiter(resource).AttemptAcquire(permitCount);
}
protected override ValueTask<RateLimitLease> AcquireAsyncCore(TResource resource, int permitCount, CancellationToken cancellationToken)
{
return GetRateLimiter(resource).AcquireAsync(permitCount, cancellationToken);
}
private RateLimiter GetRateLimiter(TResource resource)
{
RateLimitPartition<TKey> partition = _partitioner(resource);
Lazy<RateLimiter>? limiter;
lock (Lock)
{
ThrowIfDisposed();
if (!_limiters.TryGetValue(partition.PartitionKey, out limiter))
{
// Using Lazy avoids calling user code (partition.Factory) inside the lock
limiter = new Lazy<RateLimiter>(() => partition.Factory(partition.PartitionKey));
_limiters.Add(partition.PartitionKey, limiter);
// Cache is invalid now
_cacheInvalid = true;
}
}
return limiter.Value;
}
protected override void Dispose(bool disposing)
{
if (!disposing)
{
return;
}
bool alreadyDisposed = CommonDispose();
_timerTask.GetAwaiter().GetResult();
_cachedLimiters.Clear();
if (alreadyDisposed)
{
_disposeComplete.Task.GetAwaiter().GetResult();
return;
}
List<Exception>? exceptions = null;
// Safe to access _limiters outside the lock
// The timer is no longer running and _disposed is set so anyone trying to access fields will be checking that first
foreach (KeyValuePair<TKey, Lazy<RateLimiter>> limiter in _limiters)
{
try
{
limiter.Value.Value.Dispose();
}
catch (Exception ex)
{
exceptions ??= new List<Exception>();
exceptions.Add(ex);
}
}
_limiters.Clear();
_disposeComplete.TrySetResult(null);
if (exceptions is not null)
{
throw new AggregateException(exceptions);
}
}
protected override async ValueTask DisposeAsyncCore()
{
bool alreadyDisposed = CommonDispose();
await _timerTask.ConfigureAwait(false);
_cachedLimiters.Clear();
if (alreadyDisposed)
{
await _disposeComplete.Task.ConfigureAwait(false);
return;
}
List<Exception>? exceptions = null;
foreach (KeyValuePair<TKey, Lazy<RateLimiter>> limiter in _limiters)
{
try
{
await limiter.Value.Value.DisposeAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
exceptions ??= new List<Exception>();
exceptions.Add(ex);
}
}
_limiters.Clear();
_disposeComplete.TrySetResult(null);
if (exceptions is not null)
{
throw new AggregateException(exceptions);
}
}
// This handles the common state changes that Dispose and DisposeAsync need to do, the individual limiters still need to be Disposed after this call
private bool CommonDispose()
{
lock (Lock)
{
if (_disposed)
{
return true;
}
_disposed = true;
_timer.Stop();
}
return false;
}
private void ThrowIfDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(nameof(PartitionedRateLimiter));
}
}
private async Task Heartbeat()
{
lock (Lock)
{
if (_disposed)
{
return;
}
// If the cache has been invalidated we need to recreate it
if (_cacheInvalid)
{
_cachedLimiters.Clear();
_cachedLimiters.AddRange(_limiters);
_cacheInvalid = false;
}
}
List<Exception>? aggregateExceptions = null;
// cachedLimiters is safe to use outside the lock because it is only updated by the Timer
foreach (KeyValuePair<TKey, Lazy<RateLimiter>> rateLimiter in _cachedLimiters)
{
if (!rateLimiter.Value.IsValueCreated)
{
continue;
}
if (rateLimiter.Value.Value.IdleDuration is TimeSpan idleDuration && idleDuration > s_idleTimeLimit)
{
lock (Lock)
{
// Check time again under lock to make sure no one calls Acquire or WaitAsync after checking the time and removing the limiter
idleDuration = rateLimiter.Value.Value.IdleDuration ?? TimeSpan.Zero;
if (idleDuration > s_idleTimeLimit)
{
// Remove limiter from the lookup table and mark cache as invalid
// If a request for this partition comes in it will have to create a new limiter now
// And the next time the timer runs the cache needs to be updated to no longer have a reference to this limiter
_cacheInvalid = true;
_limiters.Remove(rateLimiter.Key);
// We don't want to dispose inside the lock so we need to defer it
_limitersToDispose.Add(rateLimiter.Value.Value);
}
}
}
// We know the limiter can be replenished so let's attempt to replenish tokens
else if (rateLimiter.Value.Value is ReplenishingRateLimiter replenishingRateLimiter)
{
try
{
replenishingRateLimiter.TryReplenish();
}
catch (Exception ex)
{
aggregateExceptions ??= [];
aggregateExceptions.Add(ex);
}
}
}
foreach (RateLimiter limiter in _limitersToDispose)
{
try
{
await limiter.DisposeAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
aggregateExceptions ??= new List<Exception>();
aggregateExceptions.Add(ex);
}
}
_limitersToDispose.Clear();
if (aggregateExceptions is not null)
{
throw new AggregateException(aggregateExceptions);
}
}
}
}