Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
rate_limiter: Remove Tornado in-memory backend, use Redis.
Alex Vandiver9a10c0220cbb
diff --git a/zerver/lib/rate_limiter.py b/zerver/lib/rate_limiter.pyindex fc569f70a7c..07c6173d062 100644--- a/zerver/lib/rate_limiter.py+++ b/zerver/lib/rate_limiter.py@@ -116,11 +116,7 @@ class RateLimitedUser(RateLimitedObject):self.user_id = user.idself.rate_limits = user.rate_limitsself.domain = domain- if settings.RUNNING_INSIDE_TORNADO and domain in settings.RATE_LIMITING_DOMAINS_FOR_TORNADO:- backend: type[RateLimiterBackend] | None = TornadoInMemoryRateLimiterBackend- else:- backend = None- super().__init__(backend=backend)+ super().__init__()@overridedef key(self) -> str:@@ -145,11 +141,7 @@ class RateLimitedIPAddr(RateLimitedObject):self.ip_addr = ip_addrself.ipv6_network_prefix = ipv6_network_prefixself.domain = domain- if settings.RUNNING_INSIDE_TORNADO and domain in settings.RATE_LIMITING_DOMAINS_FOR_TORNADO:- backend: type[RateLimiterBackend] | None = TornadoInMemoryRateLimiterBackend- else:- backend = None- super().__init__(backend=backend)+ super().__init__()@overridedef key(self) -> str:@@ -219,132 +211,6 @@ class RateLimiterBackend(ABC):pass-class TornadoInMemoryRateLimiterBackend(RateLimiterBackend):- # reset_times[rule][key] is the time at which the event- # request from the rate-limited key will be accepted.- reset_times: dict[tuple[int, int], dict[str, float]] = {}-- # last_gc_time is the last time when the garbage was- # collected from reset_times for rule (time_window, max_count).- last_gc_time: dict[tuple[int, int], float] = {}-- # timestamps_blocked_until[key] contains the timestamp- # up to which the key has been blocked manually.- timestamps_blocked_until: dict[str, float] = {}-- @classmethod- def _garbage_collect_for_rule(cls, now: float, time_window: int, max_count: int) -> None:- keys_to_delete = []- reset_times_for_rule = cls.reset_times.get((time_window, max_count), None)- if reset_times_for_rule is None:- return-- keys_to_delete = [- entity_key- for entity_key in reset_times_for_rule- if reset_times_for_rule[entity_key] < now- ]-- for entity_key in keys_to_delete:- del reset_times_for_rule[entity_key]-- if not reset_times_for_rule:- del cls.reset_times[(time_window, max_count)]-- @classmethod- def need_to_limit(cls, entity_key: str, time_window: int, max_count: int) -> tuple[bool, float]:- """- Returns a tuple of `(rate_limited, time_till_free)`.- For simplicity, we have loosened the semantics here from- - each key may make at most `count * (t / window)` request within any t- time interval.- to- - each key may make at most `count * [(t / window) + 1]` request within- any t time interval.- Thus, we only need to store reset_times for each key which will be less- memory-intensive. This also has the advantage that you can only ever- lock yourself out completely for `window / count` seconds instead of- `window` seconds.- """- now = time.time()-- # Remove all timestamps from `reset_times` that are too old.- if cls.last_gc_time.get((time_window, max_count), 0) <= now - time_window / max_count:- cls.last_gc_time[(time_window, max_count)] = now- cls._garbage_collect_for_rule(now, time_window, max_count)-- reset_times_for_rule = cls.reset_times.setdefault((time_window, max_count), {})- new_reset = max(reset_times_for_rule.get(entity_key, now), now) + time_window / max_count-- if new_reset > now + time_window:- # Compute for how long the bucket will remain filled.- time_till_free = new_reset - time_window - now- return True, time_till_free-- reset_times_for_rule[entity_key] = new_reset- return False, 0.0-- @classmethod- @override- def get_api_calls_left(- cls, entity_key: str, range_seconds: int, max_calls: int- ) -> tuple[int, float]:- now = time.time()- if (range_seconds, max_calls) in cls.reset_times and entity_key in cls.reset_times[- (range_seconds, max_calls)- ]:- reset_time = cls.reset_times[(range_seconds, max_calls)][entity_key]- else:- return max_calls, 0-- calls_remaining = (now + range_seconds - reset_time) * max_calls // range_seconds- return int(calls_remaining), reset_time - now-- @classmethod- @override- def block_access(cls, entity_key: str, seconds: int) -> None:- now = time.time()- cls.timestamps_blocked_until[entity_key] = now + seconds-- @classmethod- @override- def unblock_access(cls, entity_key: str) -> None:- del cls.timestamps_blocked_until[entity_key]-- @classmethod- @override- def clear_history(cls, entity_key: str) -> None:- for reset_times_for_rule in cls.reset_times.values():- reset_times_for_rule.pop(entity_key, None)- cls.timestamps_blocked_until.pop(entity_key, None)-- @classmethod- @override- def rate_limit_entity(- cls, entity_key: str, rules: list[tuple[int, int]], max_api_calls: int, max_api_window: int- ) -> tuple[bool, float, int, float]:- now = time.time()- if entity_key in cls.timestamps_blocked_until:- # Check whether the key is manually blocked.- if now < cls.timestamps_blocked_until[entity_key]:- blocking_ttl = cls.timestamps_blocked_until[entity_key] - now- return True, blocking_ttl, 0, 0.0- else:- del cls.timestamps_blocked_until[entity_key]-- assert rules- for time_window, max_count in rules:- ratelimited, time_till_free = cls.need_to_limit(entity_key, time_window, max_count)-- if ratelimited:- return True, time_till_free, 0, 0.0-- calls_remaining, secs_to_reset = cls.get_api_calls_left(- entity_key, max_api_window, max_api_calls- )- return False, 0.0, calls_remaining, secs_to_reset--class RedisRateLimiterBackend(RateLimiterBackend):_script: redis.commands.core.Script | None = Nonediff --git a/zerver/tests/test_rate_limiter.py b/zerver/tests/test_rate_limiter.pyindex b08fbc0f54d..fbd6a24b1c1 100644--- a/zerver/tests/test_rate_limiter.py+++ b/zerver/tests/test_rate_limiter.py@@ -11,7 +11,6 @@ from zerver.lib.rate_limiter import (RateLimitedUser,RateLimiterBackend,RedisRateLimiterBackend,- TornadoInMemoryRateLimiterBackend,readable_expiry_string_for_html,readable_expiry_string_for_plaintext,)@@ -187,57 +186,6 @@ class RedisRateLimiterBackendTest(RateLimiterBackendBase):self.make_request(obj, expect_ratelimited=True, verify_api_calls_left=False)-class TornadoInMemoryRateLimiterBackendTest(RateLimiterBackendBase):- backend = TornadoInMemoryRateLimiterBackend-- @override- def api_calls_left_from_history(- self, history: list[float], max_window: int, max_calls: int, now: float- ) -> tuple[int, float]:- reset_time = 0.0- for timestamp in history:- reset_time = max(reset_time, timestamp) + (max_window / max_calls)-- calls_left = (now + max_window - reset_time) * max_calls // max_window- calls_left = int(calls_left)-- return calls_left, reset_time - now-- def test_used_in_tornado(self) -> None:- user_profile = self.example_user("hamlet")- ipv4_addr = "192.168.0.123"- ipv6_addr = "2002:DB8::21f:5bff:febf:ce22:1111"-- with self.settings(RUNNING_INSIDE_TORNADO=True):- user_obj = RateLimitedUser(user_profile, domain="api_by_user")- ipv4_obj = RateLimitedIPAddr(ipv4_addr, domain="api_by_ip")- ipv6_obj = RateLimitedIPAddr(ipv6_addr, domain="api_by_ip")-- self.assertEqual(user_obj.backend, TornadoInMemoryRateLimiterBackend)- self.assertEqual(ipv4_obj.backend, TornadoInMemoryRateLimiterBackend)- self.assertEqual(ipv6_obj.backend, TornadoInMemoryRateLimiterBackend)-- with self.settings(RUNNING_INSIDE_TORNADO=True):- user_obj = RateLimitedUser(user_profile, domain="some_domain")- ipv4_obj = RateLimitedIPAddr(ipv4_addr, domain="some_domain")- ipv6_obj = RateLimitedIPAddr(ipv6_addr, domain="some_domain")-- self.assertEqual(user_obj.backend, RedisRateLimiterBackend)- self.assertEqual(ipv4_obj.backend, RedisRateLimiterBackend)- self.assertEqual(ipv6_obj.backend, RedisRateLimiterBackend)-- def test_block_access(self) -> None:- obj = self.create_object("test", [(2, 5)])- start_time = time.time()-- obj.block_access(1)- with mock.patch("time.time", return_value=start_time):- self.make_request(obj, expect_ratelimited=True, verify_api_calls_left=False)-- with mock.patch("time.time", return_value=start_time + 1.01):- self.make_request(obj, expect_ratelimited=False, verify_api_calls_left=False)--class RateLimitedObjectsTest(ZulipTestCase):def test_user_rate_limits(self) -> None:user_profile = self.example_user("hamlet")diff --git a/zproject/computed_settings.py b/zproject/computed_settings.pyindex 2db60218f0b..13eae142307 100644--- a/zproject/computed_settings.py+++ b/zproject/computed_settings.py@@ -446,13 +446,6 @@ CACHES: dict[str, dict[str, object]] = {# Merge any local overrides with the default rules.RATE_LIMITING_RULES = {**DEFAULT_RATE_LIMITING_RULES, **RATE_LIMITING_RULES}-# List of domains that, when applied to a request in a Tornado process,-# will be handled with the separate in-memory rate limiting backend for Tornado,-# which has its own buckets separate from the default backend.-# In principle, it should be impossible to make requests to tornado that fall into-# other domains, but we use this list as an extra precaution.-RATE_LIMITING_DOMAINS_FOR_TORNADO = ["api_by_user", "api_by_ip"]-# These ratelimits are also documented publicly at# https://zulip.readthedocs.io/en/latest/production/email-gateway.htmlRATE_LIMITING_MIRROR_REALM_RULES = [