| | | 1 | | using Intentum.Distributed.RateLimiting; |
| | | 2 | | using StackExchange.Redis; |
| | | 3 | | |
| | | 4 | | namespace Intentum.Distributed.Redis; |
| | | 5 | | |
| | | 6 | | public sealed class RedisDistributedRateLimiter : IDistributedRateLimiter |
| | | 7 | | { |
| | | 8 | | private readonly IDatabase _db; |
| | | 9 | | private readonly string _keyPrefix; |
| | | 10 | | |
| | 0 | 11 | | public RedisDistributedRateLimiter(IConnectionMultiplexer connection, string keyPrefix = "intentum:ratelimit:") |
| | 0 | 12 | | { |
| | 0 | 13 | | _db = connection.GetDatabase(); |
| | 0 | 14 | | _keyPrefix = keyPrefix; |
| | 0 | 15 | | } |
| | | 16 | | |
| | | 17 | | public async Task<bool> TryAcquireAsync(string key, int limit, TimeSpan window, CancellationToken cancellationToken |
| | 0 | 18 | | { |
| | 0 | 19 | | var redisKey = $"{_keyPrefix}{key}"; |
| | 0 | 20 | | var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); |
| | 0 | 21 | | var windowStart = now - (long)window.TotalMilliseconds; |
| | | 22 | | |
| | 0 | 23 | | await _db.SortedSetRemoveRangeByScoreAsync(redisKey, double.MinValue, windowStart); |
| | 0 | 24 | | var currentCount = await _db.SortedSetLengthAsync(redisKey); |
| | | 25 | | |
| | 0 | 26 | | if (currentCount >= limit) |
| | 0 | 27 | | return false; |
| | | 28 | | |
| | 0 | 29 | | await _db.SortedSetAddAsync(redisKey, Guid.NewGuid().ToString(), now); |
| | 0 | 30 | | await _db.KeyExpireAsync(redisKey, window); |
| | 0 | 31 | | return true; |
| | 0 | 32 | | } |
| | | 33 | | } |