Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Fix rate limit 500 when the window expires between add and incr

Claudefc3ad651ae83
diff --git a/mwmbl/quota.py b/mwmbl/quota.py
index a46f297..9fd4f47 100644
--- a/mwmbl/quota.py
+++ b/mwmbl/quota.py
@@ -58,13 +58,13 @@ def check_rate_limit(user_id: int) -> bool:
key = _rate_key(user_id)
if cache.add(key, 1, timeout=1):
return True
- count = cache.incr(key)
- if count == 1:
- # Key expired between add() and incr(); Redis created it without a TTL.
- # Set the TTL now to prevent the key from leaking indefinitely.
- from django_redis import get_redis_connection
-
- get_redis_connection("default").expire(key, 1)
+ try:
+ count = cache.incr(key)
+ except ValueError:
+ # The window expired between add() and incr(), and Django's incr() raises on a
+ # missing key rather than creating it, so this request opens the next window.
+ cache.add(key, 1, timeout=1)
+ return True
return count <= RATE_LIMIT
diff --git a/test/test_search_api_key.py b/test/test_search_api_key.py
index 908cebd..a51b7a1 100644
--- a/test/test_search_api_key.py
+++ b/test/test_search_api_key.py
@@ -822,6 +822,27 @@ def test_rate_limit_allows_up_to_limit():
cache.delete(rate_key)
+def test_rate_limit_allows_a_request_when_the_window_expires_between_add_and_incr():
+ user_id = 99998
+ rate_key = f"search:rate:{user_id}"
+ cache.delete(rate_key)
+ real_add = cache.add
+ add_calls = []
+
+ def add_after_expiry(key, value, timeout):
+ # The first add() sees the previous window's key, which expires before incr().
+ add_calls.append(key)
+ if len(add_calls) == 1:
+ return False
+ return real_add(key, value, timeout)
+
+ with patch.object(cache, "add", side_effect=add_after_expiry):
+ assert check_rate_limit(user_id)
+
+ assert cache.get(rate_key) == 1, "The request should start a new window"
+ cache.delete(rate_key)
+
+
def test_increment_monthly_returns_increasing_counts():
user_id = 88888