diff options
author | Mark Haines <mark.haines@matrix.org> | 2014-09-01 17:54:54 +0100 |
---|---|---|
committer | Mark Haines <mark.haines@matrix.org> | 2014-09-02 11:16:21 +0100 |
commit | 436b3c7d0c93bd6019a576425506c4c8f2963632 (patch) | |
tree | b9ce786c415674ef691624a3c34ecadf683cbfa7 /synapse/api/ratelimiting.py | |
parent | Remove option for disabling webclient because it was confusing (diff) | |
download | synapse-436b3c7d0c93bd6019a576425506c4c8f2963632.tar.xz |
Ratelimiter object
Diffstat (limited to 'synapse/api/ratelimiting.py')
-rw-r--r-- | synapse/api/ratelimiting.py | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/synapse/api/ratelimiting.py b/synapse/api/ratelimiting.py new file mode 100644 index 0000000000..a730abd59b --- /dev/null +++ b/synapse/api/ratelimiting.py @@ -0,0 +1,36 @@ +import collections + + +class Ratelimiter(object): + + def __init__(self): + self.message_counts = collections.OrderedDict() + + def prune_message_counts(self, time_now): + for user_id in self.message_counts.keys(): + message_count, time_start, msg_rate_hz = ( + self.message_counts[user_id] + ) + time_delta = time_now - time_start + if message_count - time_delta * msg_rate_hz > 0: + break + else: + del self.message_counts[user_id] + + def send_message(self, user_id, time_now, msg_rate_hz, burst_count): + self.prune_message_counts(time_now) + message_count, time_start, _ignored = self.message_counts.pop( + user_id, (0., time_now, None), + ) + time_delta = time_now - time_start + if message_count - time_delta * msg_rate_hz < 0: + a + if message_count - (time_now - time_start) * msg_rate_hz > burst_count: + allowed = False + else: + allowed = True + message_count += 1 + self.message_counts[user_id] = ( + message_count, time_start, msg_rate_hz + ) + return allowed |