-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathRedisSlidingWindowRateLimiter.cs
155 lines (126 loc) · 5.54 KB
/
RedisSlidingWindowRateLimiter.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
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 RedisSlidingWindowRateLimiter<TKey> : RateLimiter
{
private readonly RedisSlidingWindowManager _redisManager;
private readonly RedisSlidingWindowRateLimiterOptions _options;
private readonly SlidingWindowLease 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 RedisSlidingWindowRateLimiter(TKey partitionKey, RedisSlidingWindowRateLimiterOptions 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 RedisSlidingWindowRateLimiterOptions
{
PermitLimit = options.PermitLimit,
Window = options.Window,
ConnectionMultiplexerFactory = options.ConnectionMultiplexerFactory,
};
_redisManager = new RedisSlidingWindowManager(partitionKey?.ToString() ?? string.Empty, _options);
}
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();
}
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()
{
var leaseContext = new SlidingWindowLeaseContext
{
Limit = _options.PermitLimit,
Window = _options.Window,
RequestId = Guid.NewGuid().ToString(),
};
var response = await _redisManager.TryAcquireLeaseAsync(leaseContext.RequestId);
leaseContext.Count = response.Count;
leaseContext.Allowed = response.Allowed;
if (leaseContext.Allowed)
{
return new SlidingWindowLease(isAcquired: true, leaseContext);
}
return new SlidingWindowLease(isAcquired: false, leaseContext);
}
private sealed class SlidingWindowLeaseContext
{
public long Count { get; set; }
public long Limit { get; set; }
public TimeSpan Window { get; set; }
public bool Allowed { get; set; }
public string? RequestId { get; set; }
}
private sealed class SlidingWindowLease : RateLimitLease
{
private static readonly string[] s_allMetadataNames = new[] { RateLimitMetadataName.Limit.Name, RateLimitMetadataName.Remaining.Name };
private readonly SlidingWindowLeaseContext? _context;
public SlidingWindowLease(bool isAcquired, SlidingWindowLeaseContext? 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;
}
metadata = default;
return false;
}
}
}
}