Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added support for RedisSlidingWindow statistics #50

Merged
merged 3 commits into from
Apr 21, 2023
Merged
Show file tree
Hide file tree
Changes from 2 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
44 changes: 44 additions & 0 deletions src/RedisRateLimiting/SlidingWindow/RedisSlidingWindowManager.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using StackExchange.Redis;
using System;
using System.Threading.RateLimiting;
using System.Threading.Tasks;

namespace RedisRateLimiting.Concurrency
Expand All @@ -9,6 +10,7 @@ internal class RedisSlidingWindowManager
private readonly IConnectionMultiplexer _connectionMultiplexer;
private readonly RedisSlidingWindowRateLimiterOptions _options;
private readonly RedisKey RateLimitKey;
private readonly string StatsRateLimitKey;
kamilslusarczyk marked this conversation as resolved.
Show resolved Hide resolved

private static readonly LuaScript _redisScript = LuaScript.Prepare(
@"local limit = tonumber(@permit_limit)
Expand All @@ -28,8 +30,22 @@ internal class RedisSlidingWindowManager

redis.call(""expireat"", @rate_limit_key, timestamp + window + 1)

if allowed
then
redis.call(""hincrby"", @stats_key, 'total_successful', 1)
else
redis.call(""hincrby"", @stats_key, 'total_failed', 1)
end

return { allowed, count }");

private static readonly LuaScript StatisticsScript = LuaScript.Prepare(
@"local count = redis.call(""zcard"", @rate_limit_key)
local total_successful_count = redis.call(""hget"", @stats_key, 'total_successful')
local total_failed_count = redis.call(""hget"", @stats_key, 'total_failed')

return { count, total_successful_count, total_failed_count }");

public RedisSlidingWindowManager(
string partitionKey,
RedisSlidingWindowRateLimiterOptions options)
Expand All @@ -38,6 +54,7 @@ public RedisSlidingWindowManager(
_connectionMultiplexer = options.ConnectionMultiplexerFactory!.Invoke();

RateLimitKey = new RedisKey($"rl:{{{partitionKey}}}");
StatsRateLimitKey = $"rl:{partitionKey}:stats";
}

internal async Task<RedisSlidingWindowResponse> TryAcquireLeaseAsync(string requestId)
Expand All @@ -54,6 +71,7 @@ internal async Task<RedisSlidingWindowResponse> TryAcquireLeaseAsync(string requ
rate_limit_key = RateLimitKey,
permit_limit = _options.PermitLimit,
window = _options.Window.TotalSeconds,
stats_key = StatsRateLimitKey,
current_time = nowUnixTimeSeconds,
unique_id = requestId,
});
Expand Down Expand Up @@ -83,6 +101,7 @@ internal RedisSlidingWindowResponse TryAcquireLease(string requestId)
rate_limit_key = RateLimitKey,
permit_limit = _options.PermitLimit,
window = _options.Window.TotalSeconds,
stats_key = StatsRateLimitKey,
current_time = nowUnixTimeSeconds,
unique_id = requestId,
});
Expand All @@ -97,6 +116,31 @@ internal RedisSlidingWindowResponse TryAcquireLease(string requestId)

return result;
}

internal RateLimiterStatistics? GetStatistics()
{
var database = _connectionMultiplexer.GetDatabase();

var response = (RedisValue[]?)database.ScriptEvaluate(
StatisticsScript,
new
{
rate_limit_key = RateLimitKey,
stats_key = StatsRateLimitKey,
});

if (response == null)
{
return null;
}

return new RateLimiterStatistics
{
CurrentAvailablePermits = _options.PermitLimit - (long)response[0],
TotalSuccessfulLeases = (long)response[1],
TotalFailedLeases = (long)response[2],
};
}
}

internal class RedisSlidingWindowResponse
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public RedisSlidingWindowRateLimiter(TKey partitionKey, RedisSlidingWindowRateLi

public override RateLimiterStatistics? GetStatistics()
{
throw new NotImplementedException();
return _redisManager.GetStatistics();
}

protected override ValueTask<RateLimitLease> AcquireAsyncCore(int permitCount, CancellationToken cancellationToken)
Expand Down
13 changes: 13 additions & 0 deletions test/RedisRateLimiting.Tests/UnitTests/SlidingWindowUnitTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ public async Task ThrowsWhenAcquiringMoreThanLimit()
[Fact]
public async Task CanAcquireAsyncResource()
{
await Fixture.ClearStatisticsAsync("Test_CanAcquireAsyncResource_SW");

using var limiter = new RedisSlidingWindowRateLimiter<string>(
"Test_CanAcquireAsyncResource_SW",
new RedisSlidingWindowRateLimiterOptions
Expand All @@ -92,6 +94,17 @@ public async Task CanAcquireAsyncResource()

using var lease2 = await limiter.AcquireAsync();
Assert.False(lease2.IsAcquired);

var stats = limiter.GetStatistics()!;
Assert.Equal(1, stats.TotalSuccessfulLeases);
Assert.Equal(1, stats.TotalFailedLeases);
Assert.Equal(0, stats.CurrentAvailablePermits);

lease.Dispose();
lease2.Dispose();

stats = limiter.GetStatistics()!;
Assert.Equal(0, stats.CurrentAvailablePermits);
}
}
}