-
Notifications
You must be signed in to change notification settings - Fork 23
/
RedisFixedWindowRateLimiter.cs
162 lines (132 loc) · 5.91 KB
/
RedisFixedWindowRateLimiter.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
using RedisRateLimiting.Concurrency;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.RateLimiting;
using System.Threading.Tasks;
namespace RedisRateLimiting
{
public class RedisFixedWindowRateLimiter<TKey> : RateLimiter
{
private readonly RedisFixedWindowManager _redisManager;
private readonly RedisFixedWindowRateLimiterOptions _options;
private readonly FixedWindowLease FailedLease = new(isAcquired: false, 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 RedisFixedWindowRateLimiter(TKey partitionKey, RedisFixedWindowRateLimiterOptions 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.Window <= TimeSpan.Zero)
{
throw new ArgumentException(string.Format("{0} must be set to a value greater than TimeSpan.Zero.", nameof(options.Window)), nameof(options));
}
if (options.ConnectionMultiplexerFactory is null)
{
throw new ArgumentException(string.Format("{0} must not be null.", nameof(options.ConnectionMultiplexerFactory)), nameof(options));
}
_options = new RedisFixedWindowRateLimiterOptions
{
PermitLimit = options.PermitLimit,
Window = options.Window,
ConnectionMultiplexerFactory = options.ConnectionMultiplexerFactory,
};
_redisManager = new RedisFixedWindowManager(partitionKey?.ToString() ?? string.Empty, _options);
}
public override RateLimiterStatistics? GetStatistics()
{
throw new NotImplementedException();
}
protected override ValueTask<RateLimitLease> AcquireAsyncCore(int permitCount, CancellationToken cancellationToken)
{
if (permitCount > _options.PermitLimit)
{
throw new ArgumentOutOfRangeException(nameof(permitCount), permitCount, string.Format("{0} permit(s) exceeds the permit limit of {1}.", permitCount, _options.PermitLimit));
}
return AcquireAsyncCoreInternal(permitCount);
}
protected override RateLimitLease AttemptAcquireCore(int permitCount)
{
// https://github.com/cristipufu/aspnetcore-redis-rate-limiting/issues/66
return FailedLease;
}
private async ValueTask<RateLimitLease> AcquireAsyncCoreInternal(int permitCount)
{
var leaseContext = new FixedWindowLeaseContext
{
Limit = _options.PermitLimit,
Window = _options.Window,
};
RedisFixedWindowResponse response;
Interlocked.Increment(ref _activeRequestsCount);
try
{
response = await _redisManager.TryAcquireLeaseAsync(permitCount);
}
finally
{
Interlocked.Decrement(ref _activeRequestsCount);
_idleSince = Stopwatch.GetTimestamp();
}
leaseContext.Count = response.Count;
leaseContext.RetryAfter = response.RetryAfter;
leaseContext.ExpiresAt = response.ExpiresAt;
return new FixedWindowLease(isAcquired: response.Allowed, leaseContext);
}
private sealed class FixedWindowLeaseContext
{
public long Count { get; set; }
public long Limit { get; set; }
public TimeSpan Window { get; set; }
public TimeSpan? RetryAfter { get; set; }
public long? ExpiresAt { get; set; }
}
private sealed class FixedWindowLease : RateLimitLease
{
private static readonly string[] s_allMetadataNames = new[] { RateLimitMetadataName.Limit.Name, RateLimitMetadataName.Remaining.Name, RateLimitMetadataName.RetryAfter.Name };
private readonly FixedWindowLeaseContext? _context;
public FixedWindowLease(bool isAcquired, FixedWindowLeaseContext? context)
{
IsAcquired = isAcquired;
_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 = Math.Max(_context.Limit - _context.Count, 0);
return true;
}
if (metadataName == RateLimitMetadataName.RetryAfter.Name && _context?.RetryAfter is not null)
{
metadata = (int)_context.RetryAfter.Value.TotalSeconds;
return true;
}
if (metadataName == RateLimitMetadataName.Reset.Name && _context?.ExpiresAt is not null)
{
metadata = _context.ExpiresAt.Value;
return true;
}
metadata = default;
return false;
}
}
}
}