Class: Berater::ConcurrencyLimiter

Inherits:
Limiter
  • Object
show all
Defined in:
lib/berater/concurrency_limiter.rb

Constant Summary collapse

LUA_SCRIPT =
Berater::LuaScript("local key = KEYS[1]\nlocal lock_key = KEYS[2]\nlocal capacity = tonumber(ARGV[1])\nlocal ts = tonumber(ARGV[2])\nlocal ttl = tonumber(ARGV[3])\nlocal cost = tonumber(ARGV[4])\nlocal lock_ids = {}\n\n-- purge stale hosts\nif ttl > 0 then\n  redis.call('ZREMRANGEBYSCORE', key, 0, ts - ttl)\nend\n\n-- check capacity\nlocal count = redis.call('ZCARD', key)\n\nif cost == 0 then\n  -- just checking count\n  table.insert(lock_ids, true)\nelseif (count + cost) <= capacity then\n  -- grab locks, one per cost\n  local lock_id = redis.call('INCRBY', lock_key, cost)\n  local locks = {}\n\n  for i = lock_id - cost + 1, lock_id do\n    table.insert(lock_ids, i)\n\n    table.insert(locks, ts)\n    table.insert(locks, i)\n  end\n\n  redis.call('ZADD', key, unpack(locks))\n  count = count + cost\n\n  if ttl > 0 then\n    redis.call('PEXPIRE', key, ttl)\n  end\nend\n\nreturn { count, unpack(lock_ids) }\n"
)

Constants inherited from Limiter

Limiter::DEFAULT_COST

Instance Attribute Summary

Attributes inherited from Limiter

#capacity, #key, #options

Instance Method Summary collapse

Methods inherited from Limiter

#==, cache_key, #limit, new, #redis, #utilization

Constructor Details

#initialize(key, capacity, **opts) ⇒ ConcurrencyLimiter

Returns a new instance of ConcurrencyLimiter.



4
5
6
7
8
9
10
11
# File 'lib/berater/concurrency_limiter.rb', line 4

def initialize(key, capacity, **opts)
  super(key, capacity, **opts)

  # truncate fractional capacity
  self.capacity = capacity.to_i

  self.timeout = opts[:timeout] || 0
end

Instance Method Details

#timeoutObject



13
14
15
# File 'lib/berater/concurrency_limiter.rb', line 13

def timeout
  options[:timeout]
end

#to_sObject



89
90
91
# File 'lib/berater/concurrency_limiter.rb', line 89

def to_s
  "#<#{self.class}(#{key}: #{capacity} at a time)>"
end