2121#
2222
2323from typing import TYPE_CHECKING , Dict , Hashable , Optional , Tuple
24+ import weakref
2425
2526from synapse .api .errors import LimitExceededError
2627from synapse .config .ratelimiting import RatelimitSettings
3334 from synapse .module_api .callbacks .ratelimit_callbacks import (
3435 RatelimitModuleApiCallbacks ,
3536 )
37+ from synapse .server import HomeServer
3638
3739
3840class Ratelimiter :
@@ -75,6 +77,7 @@ class Ratelimiter:
7577
7678 def __init__ (
7779 self ,
80+ hs : "HomeServer" ,
7881 store : DataStore ,
7982 clock : Clock ,
8083 cfg : RatelimitSettings ,
@@ -83,7 +86,7 @@ def __init__(
8386 self .clock = clock
8487 self .rate_hz = cfg .per_second
8588 self .burst_count = cfg .burst_count
86- self .store = store
89+ self .store = weakref . proxy ( store )
8790 self ._limiter_name = cfg .key
8891 self ._ratelimit_callbacks = ratelimit_callbacks
8992
@@ -94,7 +97,7 @@ def __init__(
9497 # * The rate_hz (leak rate) of this particular bucket.
9598 self .actions : Dict [Hashable , Tuple [float , float , float ]] = {}
9699
97- self .clock .looping_call (self ._prune_message_counts , 60 * 1000 )
100+ hs . register_looping_call ( self .clock .looping_call (self ._prune_message_counts , 60 * 1000 ) )
98101
99102 def _get_key (
100103 self , requester : Optional [Requester ], key : Optional [Hashable ]
@@ -348,6 +351,7 @@ async def ratelimit(
348351class RequestRatelimiter :
349352 def __init__ (
350353 self ,
354+ hs : "HomeServer" ,
351355 store : DataStore ,
352356 clock : Clock ,
353357 rc_message : RatelimitSettings ,
@@ -358,6 +362,7 @@ def __init__(
358362
359363 # The rate_hz and burst_count are overridden on a per-user basis
360364 self .request_ratelimiter = Ratelimiter (
365+ hs = hs ,
361366 store = self .store ,
362367 clock = self .clock ,
363368 cfg = RatelimitSettings (key = rc_message .key , per_second = 0 , burst_count = 0 ),
@@ -368,6 +373,7 @@ def __init__(
368373 # by the presence of rate limits in the config
369374 if rc_admin_redaction :
370375 self .admin_redaction_ratelimiter : Optional [Ratelimiter ] = Ratelimiter (
376+ hs = hs ,
371377 store = self .store ,
372378 clock = self .clock ,
373379 cfg = rc_admin_redaction ,
0 commit comments