throttling.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. from hashlib import sha1
  2. from rest_framework import throttling
  3. from rest_framework.settings import api_settings
  4. from desecapi import metrics
  5. class ScopedRatesThrottle(throttling.ScopedRateThrottle):
  6. """
  7. Like DRF's ScopedRateThrottle, but supports several rates per scope, e.g. for burst vs. sustained limit.
  8. """
  9. def parse_rate(self, rates):
  10. return [super(ScopedRatesThrottle, self).parse_rate(rate) for rate in rates]
  11. def allow_request(self, request, view):
  12. # We can only determine the scope once we're called by the view. Always allow request if scope not set.
  13. scope = getattr(view, self.scope_attr, None)
  14. if not scope:
  15. return True
  16. # Determine the allowed request rate as we normally would during
  17. # the `__init__` call.
  18. self.scope = scope
  19. self.rate = self.get_rate()
  20. if self.rate is None:
  21. return True
  22. # Amend scope with optional bucket
  23. bucket = getattr(view, self.scope_attr + '_bucket', None)
  24. if bucket is not None:
  25. self.scope += ':' + sha1(bucket.encode()).hexdigest()
  26. self.now = self.timer()
  27. self.num_requests, self.duration = zip(*self.parse_rate(self.rate))
  28. self.key = self.get_cache_key(request, view)
  29. self.history = {key: [] for key in self.key}
  30. self.history.update(self.cache.get_many(self.key))
  31. for num_requests, duration, key in zip(self.num_requests, self.duration, self.key):
  32. history = self.history[key]
  33. # Drop any requests from the history which have now passed the
  34. # throttle duration
  35. while history and history[-1] <= self.now - duration:
  36. history.pop()
  37. if len(history) >= num_requests:
  38. # Prepare variables used by the Throttle's wait() method that gets called by APIView.check_throttles()
  39. self.num_requests, self.duration, self.key, self.history = num_requests, duration, key, history
  40. response = self.throttle_failure()
  41. metrics.get('desecapi_throttle_failure').labels(request.method, scope, request.user.pk, bucket).inc()
  42. return response
  43. self.history[key] = history
  44. return self.throttle_success()
  45. def throttle_success(self):
  46. for key in self.history:
  47. self.history[key].insert(0, self.now)
  48. self.cache.set_many(self.history, max(self.duration))
  49. return True
  50. # Override the static attribute of the parent class so that we can dynamically apply override settings for testing
  51. @property
  52. def THROTTLE_RATES(self):
  53. return api_settings.DEFAULT_THROTTLE_RATES
  54. def get_cache_key(self, request, view):
  55. key = super().get_cache_key(request, view)
  56. return [f'{key}_{duration}' for duration in self.duration]