ratelimiting.py 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. # Copyright 2014-2016 OpenMarket Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import collections
  15. class Ratelimiter(object):
  16. """
  17. Ratelimit message sending by user.
  18. """
  19. def __init__(self):
  20. self.message_counts = collections.OrderedDict()
  21. def send_message(self, user_id, time_now_s, msg_rate_hz, burst_count, update=True):
  22. """Can the user send a message?
  23. Args:
  24. user_id: The user sending a message.
  25. time_now_s: The time now.
  26. msg_rate_hz: The long term number of messages a user can send in a
  27. second.
  28. burst_count: How many messages the user can send before being
  29. limited.
  30. update (bool): Whether to update the message rates or not. This is
  31. useful to check if a message would be allowed to be sent before
  32. its ready to be actually sent.
  33. Returns:
  34. A pair of a bool indicating if they can send a message now and a
  35. time in seconds of when they can next send a message.
  36. """
  37. self.prune_message_counts(time_now_s)
  38. message_count, time_start, _ignored = self.message_counts.get(
  39. user_id, (0., time_now_s, None),
  40. )
  41. time_delta = time_now_s - time_start
  42. sent_count = message_count - time_delta * msg_rate_hz
  43. if sent_count < 0:
  44. allowed = True
  45. time_start = time_now_s
  46. message_count = 1.
  47. elif sent_count > burst_count - 1.:
  48. allowed = False
  49. else:
  50. allowed = True
  51. message_count += 1
  52. if update:
  53. self.message_counts[user_id] = (
  54. message_count, time_start, msg_rate_hz
  55. )
  56. if msg_rate_hz > 0:
  57. time_allowed = (
  58. time_start + (message_count - burst_count + 1) / msg_rate_hz
  59. )
  60. if time_allowed < time_now_s:
  61. time_allowed = time_now_s
  62. else:
  63. time_allowed = -1
  64. return allowed, time_allowed
  65. def prune_message_counts(self, time_now_s):
  66. for user_id in list(self.message_counts.keys()):
  67. message_count, time_start, msg_rate_hz = (
  68. self.message_counts[user_id]
  69. )
  70. time_delta = time_now_s - time_start
  71. if message_count - time_delta * msg_rate_hz > 0:
  72. break
  73. else:
  74. del self.message_counts[user_id]