module RedisGCRA

Constants

VERSION

Public Instance Methods

limit(redis:, key:, burst:, rate:, period:, cost: 1) click to toggle source
# File lib/redis-gcra.rb, line 9
def limit(redis:, key:, burst:, rate:, period:, cost: 1)
  call redis, :perform_gcra_ratelimit, key, burst, rate, period, cost
end
peek(redis:, key:, burst:, rate:, period:) click to toggle source
# File lib/redis-gcra.rb, line 13
def peek(redis:, key:, burst:, rate:, period:)
  call redis, :inspect_gcra_ratelimit, key, burst, rate, period
end

Private Instance Methods

call(redis, script_name, key, *argv) click to toggle source
# File lib/redis-gcra.rb, line 19
def call(redis, script_name, key, *argv)
  res = call_script(redis, script_name, keys: [key], argv: argv)

  Result.new(
    limited: res[0] == 1,
    remaining: res[1],
    retry_after: parse_float_string(res[2]),
    reset_after: parse_float_string(res[3])
  )
end
call_script(redis, script_name, *args) click to toggle source
# File lib/redis-gcra.rb, line 34
def call_script(redis, script_name, *args)
  script_sha = mutex.synchronize { get_cached_sha(redis, script_name) }
  redis.evalsha script_sha, *args
end
get_cached_sha(redis, script_name) click to toggle source
# File lib/redis-gcra.rb, line 47
def get_cached_sha(redis, script_name)
  cache_key = "#{redis.id}/#{script_name}"
  redis_cache[cache_key] ||= load_script(redis, script_name)
end
load_script(redis, script_name) click to toggle source
# File lib/redis-gcra.rb, line 52
def load_script(redis, script_name)
  script_path = File.expand_path("../../vendor/#{script_name}.lua", __FILE__)
  script = File.read(script_path)
  script_sha = Digest::SHA1.hexdigest(script)
  return script_sha if redis.script(:exists, script_sha)
  redis.script(:load, File.read(script_path))
end
mutex() click to toggle source
# File lib/redis-gcra.rb, line 43
def mutex
  @mutex ||= Mutex.new
end
parse_float_string(value) click to toggle source
# File lib/redis-gcra.rb, line 30
def parse_float_string(value)
  value == "-1" ? nil : value.to_f
end
redis_cache() click to toggle source
# File lib/redis-gcra.rb, line 39
def redis_cache
  @redis_script_cache ||= {}
end