Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 11 additions & 11 deletions src/AspNetCoreRateLimit.Redis/RedisProcessingStrategy.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using AspNetCoreRateLimit;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging;
using StackExchange.Redis;
using System;
using System.Threading;
Expand All @@ -21,8 +20,7 @@ public RedisProcessingStrategy(IConnectionMultiplexer connectionMultiplexer, IRa
_logger = logger;
}

static private readonly LuaScript _atomicIncrement = LuaScript.Prepare("local count = redis.call(\"INCRBYFLOAT\", @key, tonumber(@delta)) local ttl = redis.call(\"TTL\", @key) if ttl == -1 then redis.call(\"EXPIRE\", @key, @timeout) end return count");

static private readonly LuaScript _atomicIncrement = LuaScript.Prepare("local count = redis.call(\"INCRBYFLOAT\", @key, tonumber(@delta)) local ttl = redis.call(\"TTL\", @key) if ttl == -1 then redis.call(\"EXPIRE\", @key, @timeout) end return { 'count', count, 'ttl', ttl }");
public override async Task<RateLimitCounter> ProcessRequestAsync(ClientRequestIdentity requestIdentity, RateLimitRule rule, ICounterKeyBuilder counterKeyBuilder, RateLimitOptions rateLimitOptions, CancellationToken cancellationToken = default)
{
var counterId = BuildCounterKey(requestIdentity, rule, counterKeyBuilder, rateLimitOptions);
Expand All @@ -31,16 +29,18 @@ public override async Task<RateLimitCounter> ProcessRequestAsync(ClientRequestId

public async Task<RateLimitCounter> IncrementAsync(string counterId, TimeSpan interval, Func<double> RateIncrementer = null)
{
var now = DateTime.UtcNow;
var numberOfIntervals = now.Ticks / interval.Ticks;
var intervalStart = new DateTime(numberOfIntervals * interval.Ticks, DateTimeKind.Utc);

_logger.LogDebug("Calling Lua script. {counterId}, {timeout}, {delta}", counterId, interval.TotalSeconds, 1D);
var count = await _connectionMultiplexer.GetDatabase().ScriptEvaluateAsync(_atomicIncrement, new { key = new RedisKey(counterId), timeout = interval.TotalSeconds, delta = RateIncrementer?.Invoke() ?? 1D });
var cacheStart = DateTime.UtcNow;
var cached = await _connectionMultiplexer.GetDatabase().ScriptEvaluateAsync(_atomicIncrement, new { key = new RedisKey(counterId), timeout = interval.TotalSeconds, delta = RateIncrementer?.Invoke() ?? 1D });
var responseDict = cached.ToDictionary();
var ttlSeconds = (int)responseDict["ttl"];
if (ttlSeconds != -1)
cacheStart = cacheStart.Add(-interval).AddSeconds(ttlSeconds); // Subtract the amount of seconds the interval adds, then add the amount of seconds still left to live.
var count = (double)responseDict["count"];
return new RateLimitCounter
{
Count = (double)count,
Timestamp = intervalStart
Count = count,
Timestamp = cacheStart
};
}
}
Expand Down