class Berater::ConcurrencyLimiter

Constants

LUA_SCRIPT

Public Class Methods

new(key, capacity, **opts) click to toggle source
Calls superclass method
# 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

Public Instance Methods

timeout() click to toggle source
# File lib/berater/concurrency_limiter.rb, line 13
def timeout
  options[:timeout]
end
to_s() click to toggle source
# File lib/berater/concurrency_limiter.rb, line 89
def to_s
  "#<#{self.class}(#{key}: #{capacity} at a time)>"
end

Protected Instance Methods

acquire_lock(capacity, cost) click to toggle source
# File lib/berater/concurrency_limiter.rb, line 66
          def acquire_lock(capacity, cost)
  # round fractional capacity and cost
  capacity = capacity.to_i
  cost = cost.ceil

  # timestamp in milliseconds
  ts = (Time.now.to_f * 10**3).to_i

  count, *lock_ids = LUA_SCRIPT.eval(
    redis,
    [ cache_key, self.class.cache_key('lock_id') ],
    [ capacity, ts, @timeout, cost ]
  )

  raise Overloaded if lock_ids.empty?

  release_fn = if cost > 0
    proc { redis.zrem(cache_key, lock_ids) }
  end

  Lock.new(capacity, count, release_fn)
end

Private Instance Methods

timeout=(timeout) click to toggle source
# File lib/berater/concurrency_limiter.rb, line 17
        def timeout=(timeout)
  timeout = 0 if timeout == Float::INFINITY
  @timeout = Berater::Utils.to_msec(timeout)
end