Skip to content

Commit

Permalink
Return combined count for sliding window
Browse files Browse the repository at this point in the history
  • Loading branch information
fredriklengstrand committed Mar 31, 2023
1 parent 003be2f commit 635b55a
Showing 1 changed file with 9 additions and 7 deletions.
16 changes: 9 additions & 7 deletions rate.hsl
Original file line number Diff line number Diff line change
Expand Up @@ -38,16 +38,12 @@ function rate_sliding_window($namespace, $entry, $count, $interval) {
if ($response["error"]) throw Exception($response["error"]);
$currentWindowCount = number($response["reply"]);

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

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

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

Expand All @@ -57,7 +53,13 @@ function rate_sliding_window($namespace, $entry, $count, $interval) {
$lastWindowCount = number($response["reply"]);

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

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

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

Expand Down

0 comments on commit 635b55a

Please sign in to comment.