summary refs log tree commit diff
path: root/synapse/handlers/_base.py
diff options
context:
space:
mode:
authorMark Haines <mark.haines@matrix.org>2014-09-02 17:57:04 +0100
committerMark Haines <mark.haines@matrix.org>2014-09-02 17:57:04 +0100
commitc7a7cdf7346c9268b1d4f483b31e1fdc39b6d7e0 (patch)
tree0981bb47e64f47f3a4e57b4010f5fcb4743824d0 /synapse/handlers/_base.py
parentTest ratelimiter (diff)
downloadsynapse-c7a7cdf7346c9268b1d4f483b31e1fdc39b6d7e0.tar.xz
Add ratelimiting function to basehandler
Diffstat (limited to 'synapse/handlers/_base.py')
-rw-r--r--synapse/handlers/_base.py17
1 files changed, 17 insertions, 0 deletions
diff --git a/synapse/handlers/_base.py b/synapse/handlers/_base.py
index b37c8be964..dc1298366e 100644
--- a/synapse/handlers/_base.py
+++ b/synapse/handlers/_base.py
@@ -14,6 +14,7 @@
 # limitations under the License.
 
 from twisted.internet import defer
+from synapse.api.errors import cs_error, Codes
 
 class BaseHandler(object):
 
@@ -25,8 +26,24 @@ class BaseHandler(object):
         self.room_lock = hs.get_room_lock_manager()
         self.state_handler = hs.get_state_handler()
         self.distributor = hs.get_distributor()
+        self.ratelimiter = hs.get_ratelimiter()
+        self.clock = hs.get_clock()
         self.hs = hs
 
+    def ratelimit(self, user_id):
+        time_now = self.clock.time()
+        allowed, time_allowed = self.ratelimiter.send_message(
+            user_id, time_now,
+            msg_rate_hz=self.hs.config.rc_messages_per_second,
+            burst_count=self.hs.config.rc_messsage_burst_count,
+        )
+        if not allowed:
+            raise cs_error(
+                "Limit exceeded",
+                Codes.M_LIMIT_EXCEEDED,
+                retry_after_ms=1000*(time_allowed - time_now),
+            )
+
 
 class BaseRoomHandler(BaseHandler):