class NimbleThrottler
Attributes
cache_store[RW]
data[RW]
default_limit[R]
default_period[R]
Public Class Methods
configure(&block)
click to toggle source
# File lib/nimble_throttler.rb, line 24 def configure(&block) class_eval(&block) if block_given? end
endpoints()
click to toggle source
# File lib/nimble_throttler.rb, line 32 def endpoints instance.data.keys end
exceed_limit?(req)
click to toggle source
# File lib/nimble_throttler.rb, line 43 def exceed_limit?(req) key, = key_and_expires_in(req) count = instance.cache_store.read(key).to_i count > instance.data[req.path][:limit].to_i end
expires_in(req)
click to toggle source
# File lib/nimble_throttler.rb, line 49 def expires_in(req) _, expires_in = key_and_expires_in(req) expires_in end
key_and_expires_in(req)
click to toggle source
# File lib/nimble_throttler.rb, line 54 def key_and_expires_in(req) period = (instance.data[req.path][:period] || instance.default_period).to_i epoch_time = Time.current.to_i expires_in = (period - (epoch_time % period) + 1) key = "req/ip:#{req.ip}:#{(epoch_time / period)}" [key, expires_in] end
new()
click to toggle source
# File lib/nimble_throttler.rb, line 12 def initialize @data = {} @cache_store = ActiveSupport::Cache::MemoryStore.new @default_period = 1.hours @default_limit = 100 end
throttle(endpoint, opts)
click to toggle source
# File lib/nimble_throttler.rb, line 28 def throttle(endpoint, opts) instance.add(endpoint, opts) end
throttle_for(req)
click to toggle source
# File lib/nimble_throttler.rb, line 36 def throttle_for(req) key, expires_in = key_and_expires_in(req) result = instance.cache_store.increment(key, 1, expires_in: expires_in) instance.cache_store.write(key, 1, expires_in: expires_in) if result.nil? result || 1 end
Public Instance Methods
add(key, value)
click to toggle source
# File lib/nimble_throttler.rb, line 19 def add(key, value) @data[key] = value end