Module: Komrade::RateLimiter
Constant Summary collapse
Instance Method Summary collapse
- #breaker(attr, value, bucket, &blk) ⇒ Object
- #breaks ⇒ Object
- #check(data, attr, value, &blk) ⇒ Object
- #increment(data, attr, timestamp) ⇒ Object
- #limiter(attr, value, bucket, &blk) ⇒ Object
- #limits ⇒ Object
- #stamp(data, attr, bucket) ⇒ Object
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) = stamp(breaks, attr, bucket) check(breaks, attr, value) do begin yield rescue => e increment(breaks, attr, ) raise end end end |
#breaks ⇒ Object
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, ) data[:timestamps][attr] = 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) = stamp(limits, attr, bucket) increment(limits, attr, ) check(limits, attr, value) do yield end end |
#limits ⇒ Object
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) = Time.now.to_i / bucket data[:counts][attr] = 0 unless data[:timestamps][attr] == end |