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

Pass current time as a parameter in RedisTokenBucketManager #156

Merged
merged 1 commit into from
Feb 16, 2024
Merged
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
13 changes: 4 additions & 9 deletions src/RedisRateLimiting/TokenBucket/RedisTokenBucketManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,7 @@ internal class RedisTokenBucketManager
local rate = tonumber(@tokens_per_period)
local period = tonumber(@replenish_period)
local requested = tonumber(@permit_count)

-- Even though it is the default since Redis 5, we explicitly enable command replication.
-- This ensures that non-deterministic commands like 'TIME' are replicated by effect.
redis.replicate_commands()

-- Retrieve the current time as unix timestamp with millisecond accuracy.
local time = redis.call('TIME')
local now = math.floor((time[1] * 1000) + (time[2] / 1000))
local now = tonumber(@current_time)

-- Load the current state from Redis. We use MGET to save a round-trip.
local state = redis.call('MGET', @rate_limit_key, @timestamp_key)
Expand Down Expand Up @@ -97,6 +90,7 @@ internal async Task<RedisTokenBucketResponse> TryAcquireLeaseAsync()
token_limit = (RedisValue)_options.TokenLimit,
replenish_period = (RedisValue)_options.ReplenishmentPeriod.TotalMilliseconds,
permit_count = (RedisValue)1D,
current_time = (RedisValue)DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
});

var result = new RedisTokenBucketResponse();
Expand Down Expand Up @@ -125,6 +119,7 @@ internal RedisTokenBucketResponse TryAcquireLease()
token_limit = (RedisValue)_options.TokenLimit,
replenish_period = (RedisValue)_options.ReplenishmentPeriod.TotalMilliseconds,
permit_count = (RedisValue)1D,
current_time = (RedisValue)DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
});

var result = new RedisTokenBucketResponse();
Expand All @@ -146,4 +141,4 @@ internal class RedisTokenBucketResponse
internal long Count { get; set; }
internal int RetryAfter { get; set; }
}
}
}
Loading