Skip to content

Commit

Permalink
Merge pull request #156 from altso/master
Browse files Browse the repository at this point in the history
Pass current time as a parameter in `RedisTokenBucketManager`
  • Loading branch information
cristipufu authored Feb 16, 2024
2 parents 0be3a10 + f7b1bab commit e7715fd
Showing 1 changed file with 4 additions and 9 deletions.
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; }
}
}
}

0 comments on commit e7715fd

Please sign in to comment.