implement token bucket rate limiting
This commit is contained in:
@@ -180,13 +180,13 @@ class AnonymousUser
|
||||
def enable_sequential_post_navigation
|
||||
true
|
||||
end
|
||||
|
||||
def api_regen_multiplier
|
||||
1
|
||||
end
|
||||
|
||||
def api_hourly_limit(idempotent = false)
|
||||
if idempotent
|
||||
500
|
||||
else
|
||||
5
|
||||
end
|
||||
def api_burst_limit
|
||||
5
|
||||
end
|
||||
|
||||
def statement_timeout
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
module ApiLimiter
|
||||
def self.idempotent?(method)
|
||||
case method
|
||||
when "POST", "PUT", "DELETE", "PATCH"
|
||||
false
|
||||
|
||||
else
|
||||
true
|
||||
end
|
||||
end
|
||||
|
||||
def throttled?(user_key, http_method = "GET")
|
||||
idempotent = ApiLimiter.idempotent?(http_method)
|
||||
key = "api/#{user_key}/#{Time.now.hour}/#{idempotent}"
|
||||
MEMCACHE.fetch(key, 1.hour, :raw => true) {0}
|
||||
MEMCACHE.incr(key).to_i > CurrentUser.user.api_hourly_limit(idempotent)
|
||||
end
|
||||
|
||||
def remaining_hourly_limit(user_key, idempotent = true)
|
||||
key = "api/#{user_key}/#{Time.now.hour}/#{idempotent}"
|
||||
requests = MEMCACHE.fetch(key, 1.hour, :raw => true) {0}.to_i
|
||||
CurrentUser.user.api_hourly_limit(idempotent) - requests
|
||||
end
|
||||
|
||||
module_function :throttled?, :remaining_hourly_limit
|
||||
end
|
||||
@@ -17,5 +17,6 @@ class DailyMaintenance
|
||||
Tag.clean_up_negative_post_counts!
|
||||
PostApproval.prune!
|
||||
SuperVoter.init!
|
||||
TokenBucket.prune!
|
||||
end
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user