Skip to content

Commit

Permalink
Implement sliding window type
Browse files Browse the repository at this point in the history
  • Loading branch information
fredriklengstrand committed Mar 28, 2023
1 parent 56d32d2 commit 7e8ca43
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
2 changes: 1 addition & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
CMAKE_MINIMUM_REQUIRED(VERSION 3.0)

PROJECT("rate-redis" VERSION 1.0.0)
PROJECT("rate-redis" VERSION 1.1.0)

IF (EXISTS "${CMAKE_CURRENT_BINARY_DIR}/CPACK_GENERATOR.txt")
FILE(STRINGS ${CMAKE_CURRENT_BINARY_DIR}/CPACK_GENERATOR.txt CPACK_GENERATOR)
Expand Down
36 changes: 36 additions & 0 deletions rate.hsl
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,39 @@ function rate($namespace, $entry, $count, $interval) {
if ($response["error"]) throw Exception($response["error"]);
return true;
}

function rate_sliding_window($namespace, $entry, $count, $interval) {
$time = time();

$currentWindow = floor($time / $interval);
$response = redisClusterCommand("GET", "$namespace:$entry:$currentWindow");
if ($response["error"]) throw Exception($response["error"]);
$currentWindowCount = number($response["reply"]);

if ($count === 0) {
return $currentWindowCount;
}

if ($currentWindowCount === 0) {
$response = redisClusterCommand("SET", "$namespace:$entry:$currentWindow", "0", "EX", string($interval * 2));
if ($response["error"]) throw Exception($response["error"]);
}

if ($currentWindowCount >= $count) {
return false;
}

$lastWindow = round(($time - $interval) / $interval);
$response = redisClusterCommand("GET", "$namespace:$entry:$lastWindow");
if ($response["error"]) throw Exception($response["error"]);
$lastWindowCount = number($response["reply"]);

$elapsedTimePercentage = ($time % $interval) / $interval;
if ($lastWindowCount * (1 - $elapsedTimePercentage) + $currentWindowCount >= $count) {
return false;
}

$response = redisClusterCommand("INCR", "$namespace:$entry:$currentWindow");
if ($response["error"]) throw Exception($response["error"]);
return true;
}

0 comments on commit 7e8ca43

Please sign in to comment.