Module: Komrade::RateLimiter

Extended by:
RateLimiter
Included in:
RateLimiter
Defined in:
lib/komrade-client/rate_limiter.rb

Constant Summary collapse

Unavailable =
Class.new(Komrade::Error)

Instance Method Summary collapse

Instance Method Details

#breaker(attr, value, bucket, &blk) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
# File 'lib/komrade-client/rate_limiter.rb', line 42

def breaker(attr, value, bucket, &blk)
  timestamp = stamp(breaks, attr, bucket)
  check(breaks, attr, value) do
    begin
      yield
    rescue => e
      increment(breaks, attr, timestamp)
      raise
    end
  end
end

#breaksObject



11
12
13
# File 'lib/komrade-client/rate_limiter.rb', line 11

def breaks
  @breaks ||= {counts: Hash.new(0), timestamps: Hash.new(0)}
end

#check(data, attr, value, &blk) ⇒ Object



26
27
28
29
30
31
32
# File 'lib/komrade-client/rate_limiter.rb', line 26

def check(data, attr, value, &blk)
  if value == 0 || data[:counts][attr] < value
    yield
  else
    raise(Unavailable, attr)
  end
end

#increment(data, attr, timestamp) ⇒ Object



21
22
23
24
# File 'lib/komrade-client/rate_limiter.rb', line 21

def increment(data, attr, timestamp)
  data[:timestamps][attr] = timestamp
  data[:counts][attr] += 1
end

#limiter(attr, value, bucket, &blk) ⇒ Object



34
35
36
37
38
39
40
# File 'lib/komrade-client/rate_limiter.rb', line 34

def limiter(attr, value, bucket, &blk)
  timestamp = stamp(limits, attr, bucket)
  increment(limits, attr, timestamp)
  check(limits, attr, value) do
    yield
  end
end

#limitsObject



7
8
9
# File 'lib/komrade-client/rate_limiter.rb', line 7

def limits
  @limits ||= {counts: Hash.new(0), timestamps: Hash.new(0)}
end

#stamp(data, attr, bucket) ⇒ Object



15
16
17
18
19
# File 'lib/komrade-client/rate_limiter.rb', line 15

def stamp(data, attr, bucket)
  timestamp = Time.now.to_i / bucket
  data[:counts][attr] = 0 unless data[:timestamps][attr] == timestamp
  timestamp
end