-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathRedisConcurrencyRateLimiter.cs
323 lines (261 loc) · 10.8 KB
/
RedisConcurrencyRateLimiter.cs
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
using RedisRateLimiting.Concurrency;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.RateLimiting;
using System.Threading.Tasks;
namespace RedisRateLimiting
{
public class RedisConcurrencyRateLimiter<TKey> : RateLimiter
{
private readonly RedisConcurrencyManager _redisManager;
private readonly RedisConcurrencyRateLimiterOptions _options;
private readonly ConcurrentQueue<Request> _queue = new();
private readonly PeriodicTimer? _periodicTimer;
private bool _disposed;
private readonly ConcurrencyLease FailedLease = new(false, null, null);
private int _activeRequestsCount;
private long _idleSince = Stopwatch.GetTimestamp();
public override TimeSpan? IdleDuration => Interlocked.CompareExchange(ref _activeRequestsCount, 0, 0) > 0
? null
: Stopwatch.GetElapsedTime(_idleSince);
public RedisConcurrencyRateLimiter(TKey partitionKey, RedisConcurrencyRateLimiterOptions options)
{
if (options is null)
{
throw new ArgumentNullException(nameof(options));
}
if (options.PermitLimit <= 0)
{
throw new ArgumentException(string.Format("{0} must be set to a value greater than 0.", nameof(options.PermitLimit)), nameof(options));
}
if (options.QueueLimit < 0)
{
throw new ArgumentException(string.Format("{0} must be set to a value greater than 0.", nameof(options.QueueLimit)), nameof(options));
}
if (options.ConnectionMultiplexerFactory is null)
{
throw new ArgumentException(string.Format("{0} must not be null.", nameof(options.ConnectionMultiplexerFactory)), nameof(options));
}
_options = new RedisConcurrencyRateLimiterOptions
{
ConnectionMultiplexerFactory = options.ConnectionMultiplexerFactory,
PermitLimit = options.PermitLimit,
QueueLimit = options.QueueLimit,
TryDequeuePeriod = options.TryDequeuePeriod,
};
_redisManager = new RedisConcurrencyManager(partitionKey?.ToString() ?? string.Empty, _options);
if (_options.QueueLimit > 0)
{
_periodicTimer = new PeriodicTimer(_options.TryDequeuePeriod);
_ = StartDequeueTimerAsync(_periodicTimer);
}
}
public override RateLimiterStatistics? GetStatistics()
{
return _redisManager.GetStatistics();
}
protected override async ValueTask<RateLimitLease> AcquireAsyncCore(int permitCount, CancellationToken cancellationToken)
{
_idleSince = Stopwatch.GetTimestamp();
if (permitCount > _options.PermitLimit)
{
throw new ArgumentOutOfRangeException(nameof(permitCount), permitCount, string.Format("{0} permit(s) exceeds the permit limit of {1}.", permitCount, _options.PermitLimit));
}
Interlocked.Increment(ref _activeRequestsCount);
try
{
return await AcquireAsyncCoreInternal(cancellationToken);
}
finally
{
Interlocked.Decrement(ref _activeRequestsCount);
_idleSince = Stopwatch.GetTimestamp();
}
}
protected override RateLimitLease AttemptAcquireCore(int permitCount)
{
// https://github.com/cristipufu/aspnetcore-redis-rate-limiting/issues/66
return FailedLease;
}
private async ValueTask<RateLimitLease> AcquireAsyncCoreInternal(CancellationToken cancellationToken)
{
var leaseContext = new ConcurencyLeaseContext
{
Limit = _options.PermitLimit,
RequestId = Guid.NewGuid().ToString(),
};
var response = await _redisManager.TryAcquireLeaseAsync(leaseContext.RequestId, tryEnqueue: true);
leaseContext.Count = response.Count;
if (response.Allowed)
{
return new ConcurrencyLease(isAcquired: true, this, leaseContext);
}
if (response.Queued)
{
Request request = new()
{
CancellationToken = cancellationToken,
LeaseContext = leaseContext,
TaskCompletionSource = new TaskCompletionSource<RateLimitLease>(),
};
if (cancellationToken.CanBeCanceled)
{
request.CancellationTokenRegistration = cancellationToken.Register(static obj =>
{
// When the request gets canceled
var request = (Request)obj!;
request.TaskCompletionSource!.TrySetCanceled(request.CancellationToken);
}, request);
}
_queue.Enqueue(request);
return await request.TaskCompletionSource.Task;
}
return new ConcurrencyLease(isAcquired: false, this, leaseContext);
}
private void Release(ConcurencyLeaseContext leaseContext)
{
if (leaseContext.RequestId is null) return;
_ = _redisManager.ReleaseLeaseAsync(leaseContext.RequestId);
}
private async Task StartDequeueTimerAsync(PeriodicTimer periodicTimer)
{
while (await periodicTimer.WaitForNextTickAsync())
{
await TryDequeueRequestsAsync();
}
}
private async Task TryDequeueRequestsAsync()
{
try
{
while (_queue.TryPeek(out var request))
{
if (request.TaskCompletionSource!.Task.IsCompleted)
{
try
{
// The request was canceled while in the pending queue
await _redisManager.ReleaseQueueLeaseAsync(request.LeaseContext!.RequestId!);
}
finally
{
request.CancellationTokenRegistration.Dispose();
_queue.TryDequeue(out _);
}
continue;
}
var response = await _redisManager.TryAcquireLeaseAsync(request.LeaseContext!.RequestId!);
request.LeaseContext.Count = response.Count;
if (response.Allowed)
{
var pendingLease = new ConcurrencyLease(isAcquired: true, this, request.LeaseContext);
try
{
if (request.TaskCompletionSource?.TrySetResult(pendingLease) == false)
{
// The request was canceled after we acquired the lease
await _redisManager.ReleaseLeaseAsync(request.LeaseContext!.RequestId!);
}
}
finally
{
request.CancellationTokenRegistration.Dispose();
_queue.TryDequeue(out _);
}
}
else
{
// Try next time
break;
}
}
}
catch
{
// Try next time
}
}
protected override void Dispose(bool disposing)
{
if (!disposing)
{
return;
}
if (_disposed)
{
return;
}
_disposed = true;
_periodicTimer?.Dispose();
while (_queue.TryDequeue(out var request))
{
request?.CancellationTokenRegistration.Dispose();
request?.TaskCompletionSource?.TrySetResult(FailedLease);
}
base.Dispose(disposing);
}
protected override ValueTask DisposeAsyncCore()
{
Dispose(true);
return default;
}
private sealed class ConcurencyLeaseContext
{
public string? RequestId { get; set; }
public long Count { get; set; }
public long Limit { get; set; }
}
private sealed class ConcurrencyLease : RateLimitLease
{
private static readonly string[] s_allMetadataNames = new[] { RateLimitMetadataName.Limit.Name, RateLimitMetadataName.Remaining.Name };
private bool _disposed;
private readonly RedisConcurrencyRateLimiter<TKey>? _limiter;
private readonly ConcurencyLeaseContext? _context;
public ConcurrencyLease(bool isAcquired, RedisConcurrencyRateLimiter<TKey>? limiter, ConcurencyLeaseContext? context)
{
IsAcquired = isAcquired;
_limiter = limiter;
_context = context;
}
public override bool IsAcquired { get; }
public override IEnumerable<string> MetadataNames => s_allMetadataNames;
public override bool TryGetMetadata(string metadataName, out object? metadata)
{
if (metadataName == RateLimitMetadataName.Limit.Name && _context is not null)
{
metadata = _context.Limit.ToString();
return true;
}
if (metadataName == RateLimitMetadataName.Remaining.Name && _context is not null)
{
metadata = _context.Limit - _context.Count;
return true;
}
metadata = default;
return false;
}
protected override void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
_disposed = true;
if (_context != null)
{
_limiter?.Release(_context);
}
}
}
private sealed class Request
{
public CancellationToken CancellationToken { get; set; }
public ConcurencyLeaseContext? LeaseContext { get; set; }
public TaskCompletionSource<RateLimitLease>? TaskCompletionSource { get; set; }
public CancellationTokenRegistration CancellationTokenRegistration { get; set; }
}
}
}